以下是代码:
const showsToTry = [
'./assets/cards/7.jpg',
'./assets/cards/8.jpg',
'./assets/cards/9.jpg',
'./assets/cards/10.jpg',
'./assets/cards/11.jpg',
'./assets/cards/12.jpg',
]
const showsToTrySection = document.querySelector('#shows-to-try')
showsToTry.forEach(song => {
const showsToTrySongs = document.createElement('div')
showsToTrySongs.className = 'card hp-subhero-card col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2'
showsToTrySongs.innerHTML = `
<img src="${song}" class="card-img-top pt-2 img-fluid" alt="...">
<div class="card-body">
<p class="hp-subhero-title">Purple Rain</p>
<p class="hp-subhero-subtitle">Another song from my soul</p>
</div>`
showsToTrySection.appendChild(showsToTrySongs)
})
我想为这个数组中的每个图片添加一个唯一的id和一个唯一内容。我该怎么做?非常感谢
您可以在循环中使用数组索引作为id的一个不同部分。
showsToTry.forEach((song, i) => {
/* ... */
showsToTrySongs.id = `song_${i}`
/* ... */
}
这将给出"song_0"
-"song_5"
的ID
const showsToTry = [
'./assets/cards/7.jpg',
'./assets/cards/8.jpg',
'./assets/cards/9.jpg',
'./assets/cards/10.jpg',
'./assets/cards/11.jpg',
'./assets/cards/12.jpg',
]
const showsToTrySection = document.querySelector('#shows-to-try')
showsToTry.forEach((song, i) => {
const showsToTrySongs = document.createElement('div')
showsToTrySongs.id = `song_${i}`
showsToTrySongs.className = 'card hp-subhero-card col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2'
showsToTrySongs.innerHTML = `
<img src="${song}" class="card-img-top pt-2 img-fluid" alt="...">
<div class="card-body">
<p class="hp-subhero-title">Purple Rain</p>
<p class="hp-subhero-subtitle">Another song from my soul</p>
</div>`
showsToTrySection.appendChild(showsToTrySongs)
})
<div id="shows-to-try">
</div>