使用jQuery动态添加行和列到表中 [英] Adding rows and columns to a table dynamically with jQuery

查看:91
本文介绍了使用jQuery动态添加行和列到表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JavaScript代码:

I have the following JavaScript code:

function addRowToTable()
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  // if there's no header row in the table, then iteration = lastRow + 1
  var iteration = lastRow;
  var row = tbl.insertRow(lastRow);

  // left cell
  var cellLeft = row.insertCell(0);
  var textNode = document.createTextNode(iteration);
  cellLeft.appendChild(textNode);

  // right cell
  var cellRight = row.insertCell(1);
  var el = document.createElement('input');
  el.type = 'text';
  el.name = 'txtRow' + iteration;
  el.id = 'txtRow' + iteration;
  el.size = 40;

  el.onkeypress = keyPressTest;
  cellRight.appendChild(el);

  // select cell
  var cellRightSel = row.insertCell(2);
  var sel = document.createElement('select');
  sel.name = 'selRow' + iteration;
  sel.options[0] = new Option('text zero', 'value0');
  sel.options[1] = new Option('text one', 'value1');
  cellRightSel.appendChild(sel);
}

如何将DOM从DOM调用转换为jQuery?任何人都可以提供示例代码。

How to translate this from DOM calls to jQuery?Can anyone give sample code .

推荐答案

我将避免使用HTML的字符串,并继续创建像以前一样的DOM元素。 jQuery使得这很简单:

I would avoid using strings of HTML and keep creating DOM elements like you had before. jQuery makes this really easy:

var row = $("<tr>");
row.append( $("<td>").text("hello") );
$("#tblSample").append(row);

请参阅 http://api.jquery.com/jQuery/#jQuery2 了解更多信息。

这篇关于使用jQuery动态添加行和列到表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆