2012-09-24 60 views
0

如何使用jQueryeach()函數生成<tr>使用jQuery生成表格行每個函數

見我嘗試以下:

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>

回答

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'); 
} 
+0

謝謝你,一個簡單的'for'循環做的。只是想知道爲什麼'each()'不起作用? – watkib

+0

'$ .each'遍歷一個集合。查看jQuery文檔和示例以更好地理解。 http://api.jquery.com/jQuery.each/ –

+0

謝謝你會的。 – watkib

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'); 
})​ 

我同意維加 - 去與外在的循環