以下代码工作正常,因为我可以根据需要添加多个“tr”行,但同时也创建了多个“tbody”元素。因此,我试图找到一种解决方案,我只创建一次“tbody”并添加多行。
$results.each(function(){
$('#tbl').append($('<tbody>')
.append($('<tr>')
.append('<td>' + Item_val + '</td>')
.append('<td>' + Name_val + '</td>')
.append('<td>' + No_val + '</td>'))
);
});
<table id="tbl">
<thead>
<tr>
<th>Item</th>
<th>Name</th>
<th>No</th>
</tr>
</thead>
</table>
最佳答案
浏览器不需要附加 tbody
并将在后台添加一个。
只需添加您的行:
results.each(function(){
$('#tbl').append($('<tr>')
.append('<td>' + Item_val + '</td>')
.append('<td>' + Name_val + '</td>')
.append('<td>' + No_val + '</td>'))
);
});
这是一个简单的测试,显示在添加 TR 时自动添加 tbody
:
HTML
<table></table>
代码:
alert($('table tbody').length); // alerts 0
$('table').append('<tr>');
alert($('table tbody').length); // alerts 1
JSFiddle: http://jsfiddle.net/m2z2cmur/
注意事项:
- 虽然 HTML5 浏览器规范规定表格可以“直接包含
TR
元素”,但所有(?)浏览器中的解析器都使用向后兼容的方法,在其中插入tbody
添加tr
时(如果没有tbody
存在)
关于javascript - 动态地向表中添加多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31442859/