例如:
{
"data": [
{
"name": "grape",
"fruit": false
},
{
"name": "orange",
"fruit": true
}
]
}
我正在循环遍历数组并将它们放在 DOM 上:
for (var i=0; i < data.length; i++) {
var item = '<li>'+data[i].name+'</li>';
$('#list').append(item)
}
我想要做的是,对于数组中 fruit
值设置为 true
的每个对象,将 is afruit
放入DOM,反之亦然。
我该怎么做?
最佳答案
有很多方法可以做到这一点,但基本上这就是要点:
// Initializing the data
const data = {
data: [{
"name": "grape",
"fruit": false
},
{
"name": "orange",
"fruit": true
}
]
}
// Getting the ul element
const ul = document.getElementById("list")
// Looping through the data array
data.data.forEach((item) => {
// creating the listItem and assigning the text node
const listItem = document.createElement('li')
item.fruit ?
listItem.appendChild(document.createTextNode("The fruit " + item.name + " is a fruit")) :
listItem.appendChild(document.createTextNode("The fruit " + item.name + " is not a fruit"));
ul.appendChild(listItem)
})
<div>
<h1>
Fruit checker
</h1>
<ul id="list"></ul>
</div>
关于javascript - 从数组中的对象获取 bool 值,然后为其分配 DOM 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55815871/