如何将数组元素的 innerHTML 分配给另一个数组中的值?
How to assign the innerHTML of array elements to the values in another array?
const posterTitle2 = document.getElementById('poster-2-title');
const posterTitle3 = document.getElementById('poster-3-title');
const posterTitle4 = document.getElementById('poster-4-title');
const posterTitleList = [posterTitle1, posterTitle2, posterTitle3, posterTitle4];
const titleList = ["The Last Days of American Crime", "Becky", "The Rising Hawk", "7500"];
我想将每个posterTitle数组元素的innerHTML设置为titleList数组中对应的值:
例如
posterTitle1.innerHTML = "The Last Days of American Crime"
我只能弄清楚如何对数组中的一个元素执行此操作(如下)。我知道会有一个简单的解决方案,但我就是看不到!
posterTitleList.forEach(element => element.innerHTML = titleList[0]);
宁愿这样尝试,给所有标题相同的 className 说 titles
并使用 className 访问所有这些,如果您不打算在任何地方使用它们,您可以完全省略 id。
const titleList = ["The Last Days of American Crime", "Becky", "The Rising Hawk", "7500"]
let titles = document.getElementsByClassName('titles')
for(let i = 0; i < titles.length; i++){
titles[i].innerHTML = titleList[i]
}
<div class="container">
<div class="titles" id='poster-2-title'></div>
<div class="titles" id='poster-3-title'></div>
<div class="titles" id='poster-4-title'></div>
</div>
posterTitleList.forEach(x=>{
x.innerHTML=titleList.shift()
})
console.log(posterTitleList)
const posterTitle2 = document.getElementById('poster-2-title');
const posterTitle3 = document.getElementById('poster-3-title');
const posterTitle4 = document.getElementById('poster-4-title');
const posterTitleList = [posterTitle1, posterTitle2, posterTitle3, posterTitle4];
const titleList = ["The Last Days of American Crime", "Becky", "The Rising Hawk", "7500"];
我想将每个posterTitle数组元素的innerHTML设置为titleList数组中对应的值:
例如
posterTitle1.innerHTML = "The Last Days of American Crime"
我只能弄清楚如何对数组中的一个元素执行此操作(如下)。我知道会有一个简单的解决方案,但我就是看不到!
posterTitleList.forEach(element => element.innerHTML = titleList[0]);
宁愿这样尝试,给所有标题相同的 className 说 titles
并使用 className 访问所有这些,如果您不打算在任何地方使用它们,您可以完全省略 id。
const titleList = ["The Last Days of American Crime", "Becky", "The Rising Hawk", "7500"]
let titles = document.getElementsByClassName('titles')
for(let i = 0; i < titles.length; i++){
titles[i].innerHTML = titleList[i]
}
<div class="container">
<div class="titles" id='poster-2-title'></div>
<div class="titles" id='poster-3-title'></div>
<div class="titles" id='poster-4-title'></div>
</div>
posterTitleList.forEach(x=>{
x.innerHTML=titleList.shift()
})
console.log(posterTitleList)