使用jQuery动态添加表格行和列

7
我有以下JavaScript代码:
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调用转换为jQuery?有人可以给出示例代码吗?
3个回答

9

我建议避免使用一长串HTML字符串,而是像以前一样创建DOM元素。jQuery让这变得非常简单:

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

请查看http://api.jquery.com/jQuery/#jQuery2获取更多信息。

3
也许可以像这个例子一样(但没有 select 标签):http://jsfiddle.net/dVBMc/3/ 更新: http://jsfiddle.net/dVBMc/6/
function addRowToTable(table, cell1, cell2) {
    var row;
    row = "<tr><td>" + cell1 + "</td><td>" + cell2 + "</td></tr>";
    table.append(row);
}

使用方法:

$(document).ready(function() {
    $('button').click(function() {
        addRowToTable($('table'), 'cell1 content', 'cell2 content');
    });
});

2

最简单的方法是使用$('#tblSample').append('<tr> ... </tr>'),手动输入html字符串(如果它是常数)。你也可以从其他地方读取html,以获得更可读的代码:

 $('#tblSample').append($('div#blank-row-container').html());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接