使用jQuery动态地向表中添加行和列

我有以下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?任何人都可以提供示例代码。

我会避免使用HTML字符串并继续像以前一样创建DOM元素。 jQuery使这很容易:

 var row = $(""); row.append( $("").text("hello") ); $("#tblSample").append(row); 

有关详细信息,请参阅http://api.jquery.com/jQuery/#jQuery2 。

也许这样的事情(但没有select ): http : //jsfiddle.net/dVBMc/3/

更新: http : //jsfiddle.net/dVBMc/6/

 function addRowToTable(table, cell1, cell2) { var row; row = "" + cell1 + "" + cell2 + ""; table.append(row); } 

用法:

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

最简单的方法是简单地使用$('#tblSample').append('

...

') ,手动输入html字符串(如果它是常量)。 您还可以从其他地方读取html,以获得更易读的代码:

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