从 Javascript 数组生成动态 HTML 表

我目前正在使用 php、javascript 和 html 制作一个网络应用程序。我对 php 进行 HTTP 后调用,以从数据库中获取必须在 html 表中显示的信息。我从我的 post 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 表的一行中显示数组中的每个索引。数组中的每个属性都将是表中的一列。我需要该表是动态的,因为数组中的索引数量将根据用户的输入而变化。任何帮助深表感谢。干杯!


编辑这就是表格应该看起来类似的内容

https://img2.mukewang.com/65045e450001a17406500443.jpg

牛魔王的故事
浏览 86回答 1
1回答

慕沐林林

首先,使用 HTML 创建一个空表。<table id="dynamic_table"></table>接下来,我们可以使用 jQuery 填充表格。var data_from_post = ...//create head by looping through keys of first object in resultvar table_head = $('<tr></tr>').wrap('<thead></thead>');$.each(data_from_post[0], function(key) {&nbsp; table_head.append('<th>' + key + '</th>');});//create body by looping through each result, then looping through each key in that resultvar table_body = $('<tbody></tbody>');$.each(data_from_post, function(index, values) {&nbsp; &nbsp; var row = $('<tr></tr>');&nbsp; &nbsp; $.each(values, function(key, value) {&nbsp; &nbsp; &nbsp; &nbsp; //here you can perform changes to the 'value' variable if you need it to be different in the table&nbsp; &nbsp; &nbsp; &nbsp; //for example, wrap the `_DwgNo` with a button&nbsp; &nbsp; &nbsp; &nbsp; if(key == '_DwgNo') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value = '<button>' + value + '</button>'&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; row.append('<td>' + value + '</td>');&nbsp; &nbsp; });&nbsp; &nbsp; table_body.append(row);});//add the head and body to the table$('#dynamic_table').append(table_head).append(table_body);这是包含此解决方案的 jsfiddlehttps://jsfiddle.net/2Lon5vj3/1/
打开App,查看更多内容
随时随地看视频慕课网APP