[英]Generate Dynamic HTML Table From Javascript Array
我目前正在使用 php、javascript 和 ZFC35FDC70D5FC69D269883A822C7 制作 web 应用程序。 我发布 http 调用 php 从我的数据库中获取我必须在 html 表中显示的信息。 我从我的帖子 http 调用中得到以下数据:
0:
DwgFile: "\\TEAM\wwwroot\dwfs\A-104589 ELEVATOR FRAME ASS'Y.idw.dwf"
DwgNo: "2A"
IssueDate: "2020-05-30"
IssueEMID: 10709
ItemID: 232002
ItemNo: "A-104589"
OrderID: 13352
Qty Total: 1
ShortDesc: "ELEVATOR FRAME ASS'Y"
SolidFile: "\\TEAM\wwwroot\dwfs\A-104589 ELEVATOR FRAME ASS'Y.iam.dwf"
_DwgNo: 2
__proto__: Object
1:
DwgFile: "\\TEAM\wwwroot\dwfs\A-104599 DRIVE SHAFT ASS'Y.idw.dwf"
DwgNo: "3A"
IssueDate: "2019-12-12"
IssueEMID: 10710
ItemID: 232012
ItemNo: "A-104599"
OrderID: 13352
Qty Total: 1
ShortDesc: "DRIVE SHAFT ASS'Y"
SolidFile: "\\TEAM\wwwroot\dwfs\A-104599 DRIVE SHAFT ASS'Y.iam.dwf"
_DwgNo: 3
如何在 html 表的行中显示数组中的每个索引。 数组中的每个属性都将是表中的一列。 我需要表格是动态的,因为数组中的索引数量会根据用户的输入而变化。 任何帮助深表感谢。 干杯!
首先,使用 HTML 创建一个空表。
<table id="dynamic_table"></table>
接下来,我们可以使用 jQuery 填写表格。
var data_from_post = ...
//create head by looping through keys of first object in result
var table_head = $('<tr></tr>').wrap('<thead></thead>');
$.each(data_from_post[0], function(key) {
table_head.append('<th>' + key + '</th>');
});
//create body by looping through each result, then looping through each key in that result
var table_body = $('<tbody></tbody>');
$.each(data_from_post, function(index, values) {
var row = $('<tr></tr>');
$.each(values, function(key, value) {
//here you can perform changes to the 'value' variable if you need it to be different in the table
//for example, wrap the `_DwgNo` with a button
if(key == '_DwgNo') {
value = '<button>' + value + '</button>'
}
row.append('<td>' + value + '</td>');
});
table_body.append(row);
});
//add the head and body to the table
$('#dynamic_table').append(table_head).append(table_body);
这是一个包含此解决方案的 jsfiddle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.