我遇到这样的情况:
var orders = [
{ID: "sampleID1", order: "string describing the first order"},
{ID: "sampleID2", order: "string describing the second order"}
];
const bill = document.querySelector("#ordersListed");
for(var x in orders) {
bill.innerHTML += orders[x].order;
}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="ordersListed"></div>
</body>
</html>
&#13;
每次单击按钮时,项目都会添加到数组中 我一直在尝试遍历数组以在HTML元素中打印每个订单。
应该在div中显示为:
描述第一个订单的字符串
描述第二顺序的字符串
我的结果:
第一顺序
第一顺序
第二顺序
答案 0 :(得分:2)
只需在数组&#39; s <br>
的每次迭代中向innerHTML
添加forEach()
即可:
var orders = [
{ID: "sampleID1", order: "string describing the first order"},
{ID: "sampleID2", order: "string describing the second order"}
];
const bill = document.querySelector("#ordersListed");
orders.forEach(o => bill.innerHTML += o.order + '<br>');
&#13;
<div id="ordersListed"></div>
&#13;
答案 1 :(得分:1)
for...in
用于迭代Object
属性,而不是Array
。使用for...of
:
var orders = [{ ID: "sampleID1", order: "string describing the first order" }, { ID: "sampleID2", order: "string describing the second order" }]
for (order of orders) {
let para = document.createElement('p')
para.textContent = order.order
ordersListed.appendChild(para)
}
#ordersListed {
background: #f8f8f8;
border: 4px dashed #ddd;
padding: 5px 15px;
}
<div id="ordersListed"></div>
注意:我更喜欢创建真正的DOM节点,因此我可以轻松添加属性并附加事件处理程序。在第二个示例中,我显示了添加标题并在点击时提醒订单ID:
var orders = [{ ID: "sampleID1", order: "string describing the first order" }, { ID: "sampleID2", order: "string describing the second order" }]
for (order of orders) {
let para = document.createElement('p')
para.textContent = order.order
para.title = order.ID
para.addEventListener('click', function() { alert(this.title) })
ordersListed.appendChild(para)
}
#ordersListed {
background: #f8f8f8;
border: 4px dashed #ddd;
padding: 5px 15px;
}
#ordersListed p {
cursor: pointer;
}
<div id="ordersListed"></div>
答案 2 :(得分:0)
怎么样:
var orders = [
{ID: "sampleID1", order: "string describing the first order"},
{ID: "sampleID2", order: "string describing the second order"}
];
for (var i = 0; i < orders.length; i++ ) {
orderListContainer.textContent += orders[i]['order'];
}
据我所知,你将数组元素而不是正确的属性附加到数组元素。