[英]How can I output a dynamic JSON array into a HTML table?
I have a function which is called on a button press and adds to an array order
: 我有一个函数,它在按下按钮时被调用,并添加到数组
order
:
var order = [];
function updateCart(item) {
var index = order.findIndex(i => i.id == item.id);
if (index != -1) {
order.splice(index, 1);
order.push(item);
} else {
order.push(item);
}
$("#test").html(JSON.stringify(order));
}
If the user adds 2 of one item and 1 of another item then order
might look like this: 如果用户添加一个项目的2个和另一个项目的1个,则
order
可能如下所示:
[{"id":1,"name":"Hawaiian","price":10,"qty":2},
{"id":2,"name":"New Yorker","price":10,"qty":1}];
I would like to be able to loop through each item in the array and have a HTML table that can show each order in an easy to read way. 我希望能够遍历数组中的每个项目,并拥有一个可以以易于阅读的方式显示每个顺序的HTML表。 For example:
例如:
<table>
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>order[0].name</td>
<td>order[0].qty</td>
</tr>
<tr>
<td>order[1].name</td>
<td>order[1].qty</td>
</tr>
</tbody>
</table>
If I pass the array to my table then it just seems to replace the entire table and not pass the values into where I have specified. 如果我将数组传递给我的表,那么它似乎只是替换整个表,而没有将值传递到我指定的位置。 See my below example:
看我下面的例子:
<script>
$("#test").html(JSON.stringify(order));
</script>
<table id="myTable">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<script>
for (var i = 0; i < order.length; i++) {
document.write("<tr>");
document.write("<td>");
document.write(order[i].name);
document.write("</td>");
document.write("</tr>");
}
</script>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
I am wondering if there is an easier way to do what I want. 我想知道是否有更简单的方法来做我想要的事情。 HTML DOM tables seem quite clunky.
HTML DOM表似乎很笨拙。 Thank you
谢谢
You can use map
. 您可以使用
map
。
HTML: HTML:
<table>
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
</thead>
<tbody id="test">
</tbody>
</table>
JS: JS:
const order = [
{ id: 1, name: "Hawaiian", price: 10, qty: 2 },
{ id: 2, name: "New Yorker", price: 10, qty: 1 }
];
const singleRow = ({ name, qty }) => `<tr><td>${name}</td><td>${qty}</td></tr>`;
$("#test").html(order.map(singleRow).join(''));
https://codepen.io/anon/pen/MReZdL https://codepen.io/anon/pen/MReZdL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.