我有一个对象数组。我希望能够在HTML中显示对象" name"通过从外部js文件调用函数来实现属性。有什么帮助吗?
let cakes = [{
name: "Savarina",
flavour: "frisca"
},
{
name: "Briosa",
flavour: "ciocolata"
}];
function renderProducts() {
cakes.forEach( function(element) {
document.body.innerHTML = `<p> ${element.name} </p>`;
});
}
&#13;
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" type="text/css" href="Stylesheets/styles.css">
</head>
<body>
<script> renderProducts();</script>
<script> src="Scripts/script.js"</script>
</body>
</html>
&#13;
答案 0 :(得分:0)
您需要指定要输出信息的位置,并附加它而不是仅设置文档html,这显然会覆盖所有内容。
创建一个输出容器,就像这样...
let cakes = [{
name: "Savarina",
flavour: "frisca"
},
{
name: "Briosa",
flavour: "ciocolata"
}];
function renderProducts() {
var output = document.querySelector("#output-div");
cakes.forEach( function(element) {
output.innerHTML += `<p> ${element.name} </p>`;
});
}
// only run the render function when the page has loaded,
// so we know the div exists.
window.addEventListener("load", renderProducts);
<div id="output-div"></div>