gpt4 book ai didi

javascript - 将json中的标题添加到html中的文本内容

转载 作者:行者123 更新时间:2023-11-30 07:49:27 28 4
gpt4 key购买 nike

我必须添加我的 data 中的所有标题在 js 中,对每个 textContent<h3 class="title"></h3>

我卡住了:(这是我的代码:

<div class="info-container">
<h3 class="title"></h3>
</div>
<div class="info-container">
<h3 class="title"></h3>
</div>
<div class="info-container">
<h3 class="title"></h3>
</div>

JS:

const data = [
{
"title": "ASD"
},
{
"title": "FGH"
}
]
const list_title = document.querySelectorAll('.title')

data.map(item => {
console.log(item.title)

//I want to add item.title to textContent of each list_title, to show each title in HTML
})

笨蛋:http://plnkr.co/edit/KF52qHjh8e6ubTCS2545?p=preview

提前感谢您的回答!

最佳答案

map() utilizes return values and actually returns a new Array of the same size.

The forEach() method doesn't actually return anything (undefined). It simply calls a provided function on each element in the array.

forEach()更适合在这里设置 textContentinnerText通过匹配索引来确定元素的属性。

index 是可选的,可以作为数组中正在处理的当前元素的 index 作为第二个参数传递。

const data = [
{
"title": "ASD"
},
{
"title": "FGH"
}
]
const list_title = document.querySelectorAll('.title')

data.forEach( (item, idx) => {
console.log(item.title)
list_title[idx].textContent = item.title;
})
<div class="info-container">
<h3 class="title"></h3>
</div>
<div class="info-container">
<h3 class="title"></h3>
</div>
<div class="info-container">
<h3 class="title"></h3>
</div>

关于javascript - 将json中的标题添加到html中的文本内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55665717/

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