无法在jQuery中创建表

时间:2009-10-20 17:57:38

标签: jquery

我会发布我尝试过的两个解决方案,以及每个解决方案失败的原因:

首先:

var table = document.createElement("table");
table.addClass("nice");
// fails because table does not have the "addClass" method

第二

var table = $(document.createElement("table"));
table.addClass("nice");
var row = table.insertRow(-1);
// fails because table does not have the "insertRow" method (it has been cleared by jQuery)

如何使用jQuery正确创建表并向其添加行和单元?

2 个答案:

答案 0 :(得分:4)

var table = $('<table>')
  .addClass('nice');

要添加行,只需创建元素并将它们附加到表格中即可。

答案 1 :(得分:1)

var table = $('<table>').addClass('foo').append( $('<tr>').append( $('<td>').text('lol') ) ).appendTo('body')

显然,它有助于将它们存储在多个变量中。