gpt4 book ai didi

javascript - 从数组中的对象获取 bool 值,然后为其分配 DOM 属性

转载 作者:行者123 更新时间:2023-12-02 23:46:57 25 4
gpt4 key购买 nike

例如:

{
"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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com