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

Javascript 将json中的标题添加到html中的文本内容,javascript,Javascript,我必须将js中我的数据中的所有标题添加到中的每个文本内容 我卡住了:(这是我的密码: <div class="info-container"> <h3 class="title"></h3> </div> <div class="info-container"> <h3 class="title"></h3> </div> <div class="info-container">

我必须将js中我的
数据
中的所有标题添加到
中的每个
文本内容

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

<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>
普朗克:


感谢您提前给出答案!

您不需要使用
map()
。您应该使用。
forEach()
接受回调,第二个参数是元素的索引。因此,您可以在
列表的该索引处设置元素的
textContent

data.forEach((item,i) => {
  list_title[i].textContent = item.title
})
这是一个工作片段

const data=[{“title”:“ASD”},{“title”:“FGH”}]
const list_title=document.queryselectoral(“.title”)
data.forEach((项目,i)=>{
列表标题[i].textContent=item.title
})

您不需要使用
map()
。您应该使用。
forEach()
在第二个参数中接受回调是元素的索引。因此您可以在
列表标题中的该索引处设置元素的
textContent

data.forEach((item,i) => {
  list_title[i].textContent = item.title
})
这是一个工作片段

const data=[{“title”:“ASD”},{“title”:“FGH”}]
const list_title=document.queryselectoral(“.title”)
data.forEach((项目,i)=>{
列表标题[i].textContent=item.title
})

map()
利用返回值并实际返回相同大小的新数组

forEach()

这里更适合通过匹配索引来设置元素的or属性

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

const数据=[
{
“标题”:“ASD”
},
{
“标题”:“FGH”
}
]
const list_title=document.queryselectoral(“.title”)
data.forEach((项目,idx)=>{
console.log(item.title)
列表标题[idx].textContent=item.title;
})

map()
利用返回值并实际返回相同大小的新数组

forEach()

这里更适合通过匹配索引来设置元素的or属性

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

const数据=[
{
“标题”:“ASD”
},
{
“标题”:“FGH”
}
]
const list_title=document.queryselectoral(“.title”)
data.forEach((项目,idx)=>{
console.log(item.title)
列表标题[idx].textContent=item.title;
})

我认为在data.map函数中进行此更改足以实现您想要的结果

data.map((item, index) => {
  console.log(list_title)
  list_title[index].innerText = item.title
  //I want to add item.title to textContent of each list_title, to show each title in HTML
})
如果您不知道将有多少本书,您可能需要进行以下更改: 在index.html中:

<body>
  <div id="info-container">

   </div>
    <script src="app.js"></script>
</body>

我希望这会有所帮助。快乐编码:)

我认为在您的data.map函数中进行此更改就足以实现您想要的结果

data.map((item, index) => {
  console.log(list_title)
  list_title[index].innerText = item.title
  //I want to add item.title to textContent of each list_title, to show each title in HTML
})
如果您不知道将有多少本书,您可能需要进行以下更改: 在index.html中:

<body>
  <div id="info-container">

   </div>
    <script src="app.js"></script>
</body>

我希望这有帮助。快乐编码:)

以前使用的
setAttribute()
在哪里?……现在答案与我的答案相同@事实上,我误解了这个问题。我以为他是在要求设置头衔属性。但是我知道他想添加
textContent
,所以我更新了。以前使用的
setAttribute()
?…现在答案与我的答案相同@事实上,我误解了这个问题。我以为他是在要求设置头衔属性。但我知道他想添加
textContent
,所以我更新了。