我发现代码按预期工作(我认为)。但是我打印数据的最后一步感觉不对。我连接 html 和 js 的方式似乎有点不对劲。有没有更好的方法来连接这个?我是否使用了错误的解决方案来打印数据?
//我在数组中使用的这个列表。
const myList = {
Germany : {name : 'Germany', capital: 'Berlin', visited: 'Checked' },
Italy : {name : 'Italy', capital: 'Rome', visited: 'Checked' },
Spain : {name : 'Spain', capital: 'Madrid', visited: 'unchecked' },
}
//我的数组
const destinations = [];
//将数据从 myList 推送到目标数组。
for(var key in myList) {
destinations.push(myList[key]);
}
//这就是我在页面上写出数据的方式。
for (var i = 0; i < destinations.length; i++) {
document.write("<li><h1>" + destinations[i].name + "</h1><p>" +
destinations[i].capital +
"<input type='checkbox'" + destinations[i].visited + ">")
};
这就是我计划在最后写的内容。
<li class="all-destinations">
<h3>destinations[i].name</h3>
<div class="container">
<label class="switch">
<input type="checkbox" destinations[i].visited>
</label>
</div>
<p>destinations[i].capital</p>
<hr>
</li>
最佳答案
您通过三种方式改进了您的代码:
- 使用
Object.values()
而不是创建[]
并推送给它。 - 您可以使用
forEach()
而不是简单的 for 循环 - 你应该使用Template Strings创建 html 字符串。
const myList = {
Germany : {name : 'Germany', capital: 'Berlin', visited: 'Checked' },
Italy : {name : 'Italy', capital: 'Rome', visited: 'Checked' },
Spain : {name : 'Spain', capital: 'Madrid', visited: 'unchecked' },
}
const list = Object.values(myList);
list.forEach(x => {
document.write(
`<li class="all-destinations">
<h3>${x.name}</h3>
<div class="container">
<label class="switch">
<input type="checkbox" ${x.visited}>
</label>
</div>
<p>${x.capital}</p>
<hr>
</li>`)
})
关于javascript - 连接来自多维数组和 HTML 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56097080/