简体   繁体   English

用jquery和json填充表

[英]populating table with jquery and json

I would like to populate an existing table with json data. 我想用json数据填充现有表。 I found an example on stackoverflow which does this but with only one column of data. 我在stackoverflow上找到了一个示例,该示例仅执行一列数据。 The json data has three sets of data which requires obviously 3 columns. json数据具有三组数据,显然需要三列。 I have experimented with only one row but the jquery code (below) incorrectly displays the table. 我只试验了一行,但是jQuery代码(如下)错误地显示了表。

<table class="table">
<tr id="row1">
<td = "col1"></td>
<td = "col2"></td>
<td = "col3"></td>

function myFunction() { 

    data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167},
            {"indx":2,"amt":3345.4,"vendor":22,"jDate":168}];

    $.each(data, function(key, value) {
        $("#row1").eq(key).find('td').text(value.indx);
        $("#row1").eq(key).find('td').text(value.amt);
        $("#row1").eq(key).find('td').text(value.jDate);

    });
}

OUTPUT IN BROWSER: 167 167 167 浏览器中的输出:167167167

It is displaying the last field in all three columns. 它显示所有三列中的最后一个字段。 Any advise on how to do get table to display the correct values would be appreciated. 任何建议如何使表显示正确的值将不胜感激。

Your code is updating ALL CELLS with value.indx , then with value.amt and finally with value.jDate ... So fast that you only see the final result. 您的代码正在使用value.indx ,然后使用value.amt以及最后使用value.jDate更新所有CELLS ...如此之快,以至于您只能看到最终结果。

I think what you want to achieve is something more like in this CodePen : 我认为您想要实现的是此CodePen中的更多内容

function myFunction() { 

    data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167},
            {"indx":2,"amt":3345.4,"vendor":22,"jDate":168}];

    $.each(data, function(key, value) {
        $("table").find('tr').eq(key).find("td").eq(0).text(value.indx);
        $("table").find('tr').eq(key).find("td").eq(1).text(value.amt);
        $("table").find('tr').eq(key).find("td").eq(2).text(value.jDate);

    });
}
myFunction();

Obviously you have to add rows dynamically into your table, because your data array may contain different amount of objects. 显然,您必须向表中动态添加行,因为数据数组可能包含不同数量的对象。 Try this code. 试试这个代码。

Here we have table which is populated with new rows for each element of data array. 在这里,我们有一个表,其中为数据数组的每个元素填充了新行。

 data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167}, {"indx":2,"amt":3344.4,"vendor":22,"jDate":168}, {"indx":3,"amt":1414.1,"vendor":21,"jDate":169}, {"indx":4,"amt":3441.3,"vendor":31,"jDate":1610}]; $.each(data, function(key, value) { var tr = $("<tr>"); tr.append($("<td>").text(value.indx)); tr.append($("<td>").text(value.amt)); tr.append($("<td>").text(value.vendor)); tr.append($("<td>").text(value.jDate)); $("#table").append(tr); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="table" border="1"> </table> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM