我们正在尝试运行具有属性(键:值)的对象集合并将其写入dom。
var productContent = {
item1: {
description: "description 1",
price: 1,
URL: "something1.com",
},
item2: {
description: "description 2",
price: 2,
URL: "something2.com",
},
我们尝试过几种不同类型的代码,例如:
var productInfo;
var insertProduct = document.getElementById("productList");
for (var i in productContent) {
console.log(productContent[i]);
productInfo += productContent[i];
}
insertProduct.innerHTML = productInfo;
似乎没有任何效果。有关如何处理此问题的任何想法?我们已经能够获得控制台中显示的属性,但其他内容并不多。
答案 0 :(得分:0)
}
。您应该在浏览器的开发人员工具中使用JS控制台来调试它。
答案 1 :(得分:0)
您的脚本中存在一些错误,您可以启动并执行以下操作:
var htmlValue = '';
for (var productKey in productContent) {
var product = productContent[productKey];
htmlValue += 'description: ' + product.description + '<br>';
htmlValue += 'price: ' + product.price + '<br>';
htmlValue += 'url: ' + product.URL + '<br><br>';
}
insertProduct.innerHTML = htmlValue;
错误:
1
for (var i in productContent) {
这只是一个强有力的建议,但您应该将i
更改为对上下文有意义的内容,例如key
,因为您正在迭代对象属性。正确命名变量可以帮助您发现代码中的错误。
2
productInfo += productContent[i]
这不是连接对象值的正确方法。第一次迭代,它将是“undefined [object Object]”。
3
insertProduct.innerHTML = productInfo;
你甚至想在这做什么?你不能只把元素放入一个对象。你必须按照你想要的方式放置代码和格式。