使用jQuery为每个函数生成表行

时间:2012-09-24 15:45:51

标签: jquery loops html-table each

我如何使用<tr> jQuery函数生成each()

请参阅下面的尝试:

HTML:

<html>
<table>
<tbody id = "table_tbody">
</tbody>
</table>
</html>

JS:

var tr_count = 10;
var tr_var ="<tr><td><input type = 'text' name= 'name'/></td>t</tr>";
$(tr_count).each(function(){
    $(tr_var).appendTo('#table_tbody');
})

这会返回一个<tr>

2 个答案:

答案 0 :(得分:4)

尝试一个简单的for循环。

//                       removed a t which should be a typo -v
var tr_var ="<tr><td><input type = 'text' name= 'name'/></td></tr>";

for (var i = 0; i < tr_count; i++ ) {
   $(tr_var).appendTo('#table_tbody');
}

答案 1 :(得分:1)

tr_count

不是数组。每个函数都试图对数组的每个元素进行操作。

试试此代码

var tr_count = 10;
var foo = new Array();
foo.push('a');
foo.push('b');
var tr_var ="<tr><td><input type = 'text' name= 'name'/></td>t</tr>";
$(foo).each(function(){
    $(tr_var).appendTo('#table_tbody');
    alert('moo');
})​

我同意Vega - 采用明确的循环