将AddEventListener放在for循环中InnerHTML中的按钮上



我正在创建一个带有一些音乐的页面,现在我正在"探索"页面上工作。你会看到大约10张从数组中随机抽取的带有音乐的卡片。一切都很顺利,直到我知道。我添加了一个按钮来启动音乐,但我似乎无法将AddEventListener放在按钮上,我只是用innerHTML制作了卡片(我知道这不是最好的选择,但这个项目仍然是实践),现在我无法使其工作。如果我把事件监听器与innerHTML按钮后的函数。我只能得到1。

function handleLoadHighlights(number) {
    for (i = 0; i < 10; i++) {
        let randomSongs = Math.floor(Math.random() * songsList.length);
        let song = songsList[randomSongs];
            let background = backgroundGradients[i];
            audioFile.src = song.audio;
            highlightsOutput.innerHTML += `
            <div class="highlighted__song" style="${background.backgroundcolor} ${background.backgroundimg}">
                <div class="highlighted__description">
                    <h3 class="highlighted__description--title">${song.title}</h3>
                    <p class="highlighted__description--para">${song.artist}</p>
                </div>
                <div class="highlighted__footer">
                    <button class="highlighted__button--play"><i class="fas fa-play-circle"></i></button>
                    <img class="highlighted__img" src="./assets/covers/${song.img}"></img>
                </div>
            </div>
            `;
    }
}

显示带有歌曲

的随机卡片的函数
const playButton = document.querySelectorAll('.highlighted__button--play');
for(i = 0; i < 10; i++) {
    playButton[i].addEventListener('click', handlePlayAudio);
}

我尝试修复它,只是总是返回最后一个c

添加歌曲的索引作为按钮的数据属性。

function handleLoadHighlights(number) {
  for (i = 0; i < 10; i++) {
    let randomSongs = Math.floor(Math.random() * songsList.length);
    let song = songsList[randomSongs];
    let background = backgroundGradients[i];
    audioFile.src = song.audio;
    highlightsOutput.innerHTML += `
            <div class="highlighted__song" style="${background.backgroundcolor} ${background.backgroundimg}">
                <div class="highlighted__description">
                    <h3 class="highlighted__description--title">${song.title}</h3>
                    <p class="highlighted__description--para">${song.artist}</p>
                </div>
                <div class="highlighted__footer">
                    <button class="highlighted__button--play" data-song="${randomSongs}"><i class="fas fa-play-circle"></i></button>
                    <img class="highlighted__img" src="./assets/covers/${song.img}"></img>
                </div>
            </div>
            `;
  }
}

然后在handlePlayAudio()中,您可以从单击的按钮中获得该索引。

let songIndex = event.target.dataset.song;
audioFile.src = songsList[songIndex].src;

eventhandlePlayAudio()的参数。

最新更新