2016-02-27 66 views
1

在準備好的DOM中,我有一個由多行組成的現有表。jQuery使用現有表映射數組

異步然後我得到一個json元素列表。

現在,json數組中的元素數量將始終等於表中的行數。

此外,json數組中的第一個元素將始終「屬於」表中的第一行,第二個元素指向第二行等等。

所以基本上有3行的表,就意味着我會得到一個JSON列表:

$.each(list,function(k,v){ 
    console.log(v.item); 
}); 

這反過來會返回三個項目值:

foo bar baz

我需要的是(堅持上面的例子),將「foo」追加到第一個tr(追加td),「bar」追加到第二個,「baz」追加到第稅務局。

所以表看起來像這樣:

Static table

是這樣算賬:

Table manipulated

任何指針是非常讚賞,有一種感覺,我已經瞎了。

回答

1

好吧讓我們一步一步解決。使用適當的表格選擇器。

var $rows = $('#myTableId tr'); //store list of rows in a variable 

$.each(list,function(index,val){ //for each value in the list 
    $rows.eq(index).append('<td>'+val+'</td>') 
    //get each row by index. 
    //This works naturally since first item goes into first row, and etc. 
    //append a td element with the content inside. 
}) 
+0

謝謝Eric,.eq是神奇的方法:) – MNorup