jquery中的append方法只显示添加的最后一个元素

时间:2016-11-21 07:28:08

标签: jquery html

我试图从json请求向表中添加数据。无论我怎样尝试,我都无法获得多个表格行。任何帮助将不胜感激。JSFiddle

HTML:

<div class="col-lg-6">
    <h2>Table</h2>
    <table class="table" id="products-table">
        <thead>
            <tr>
                <th>ASIN</th>
                <th>Title</th>
                <th>Price</th>
                <th>MPN</th>
            </tr>
        </thead>
        <tbody>
            <tr></tr>
        </tbody>
    </table>
</div> 

使用Javascript:

var prodAry = [1, 2, 3];
// create elements for table
var $tr = $('<tr>');
var $asin = $('<td>');
var $title = $('<td>');
var $price = $('<td>');
var $mpn = $('<td>');

prodAry.forEach(function(product, i) {
    var $newAsin = $asin.text(i);
    var $newTitle = $title.text(i);
    var $newPrice = $price.text(i);
    var $newMpn = $mpn.text(i);
    var $newTr = $tr.append($newAsin, $newTitle, $newPrice, $newMpn);
    $('#products-table > tbody:last-child').append($newTr);
});

2 个答案:

答案 0 :(得分:1)

根据您当前的实现,您将不断追加相同的$ touch file_1_my001 file_11_my0012 file_65_my012 $ for file in file_* ; do echo mv "$file" "${file/0/_copied_0}"; done mv file_11_my0012 file_11_my_copied_0012 mv file_1_my001 file_1_my_copied_001 mv file_65_my012 file_65_my_copied_012 元素。

您应该在$tr循环中创建元素。

forEach

Updated Fiddle

答案 1 :(得分:0)

console.log($newTr[i]);

在第15行之后添加此内容,您将看到问题。