首页 > 解决方案 > 将EventListener 添加到innerHTML

问题描述

我是 Javascript 新手,我尝试为每张卡片上的每个按钮添加一个事件侦听器,但是代码使最后一张卡片(按钮)只有事件“点击”,所以有什么方法可以通过 innerHTML 卡片实现它是代码:

let tracksRender = (track) => {

track.forEach(element => {

    //this the card that will add the button for
    let card = `<div class="card">
    <div class="image">
        <img class="image_img" src="${element.artwork_url || 'http://lorempixel.com/100/100/abstract/'}">
    </div >
        <div class="content">
            <div class="header">
                <a href="${element.permalink_url}" target="_blank">${element.title}</a>
            </div>
        </div>
</div >`;
    
    //here i add the card to DOM
    let searchResults = document.querySelector('.js-search-results');
    searchResults.innerHTML += card;

    // store the content of the button 
    let inBtn = `<i class="add icon"></i>
    <span>Add to playlist</span>`;
 
    // created button container 
    let btn = document.createElement("div");
    btn.classList.add("ui", "bottom", "attached", "button", "js-button");

    // added the content of the button 
    btn.innerHTML += inBtn;
    
    // here i add the the event Listener to the button 
    btn.addEventListener('click', () => {
        console.log("click");
    });

    //here i add the button to the last card have been created
    searchResults.querySelector(".card:last-child").append(btn);
    
});
}

和结构:

<!doctype html>
<html>

<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>SoundCloud Player</title>
    <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css'>
    <link rel='stylesheet' href='styles/main.css'>
    <style></style>
</head>

<body id="soundcloud-player">

    <div class="ui container col">
        <div class="col">
            <div class="main">
                <div class="js-search-results search-results ui cards">

                </div>
            </div>
        </div>
    </div>
    <script src="https://connect.soundcloud.com/sdk/sdk-3.3.2.js"></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js'></script>
    <script src="javascript/main.js"></script>
</body>

</html>

小提琴:https ://jsfiddle.net/y73bstju/7/

但它只会将事件添加到最后一张卡片

标签: javascripthtmldomaddeventlistener

解决方案


它可能有助于创建元素而不是附加 innerHTML:

let tracksRender = (track) => {
    
  // Select the results here, so you wont have to repeat it
  const searchResults = document.querySelector('.js-search-results');

  track.forEach(element => {

    // Create the card, give it its class and innerHTML
    const card = document.createElement('div');
    card.className = 'card';
    card.innerHTML = `<div class="image">
                          <img class="image_img" src="${element.artwork_url || 'http://lorempixel.com/100/100/abstract/'}">
                      </div >
                      <div class="content">
                          <div class="header">
                              <a href="${element.permalink_url}" target="_blank">${element.title}</a>
                          </div>
                     </div>`;
 
    // Created the button, give its classes and innerHTML
    const btn = document.createElement('div');
    btn.className = 'ui bottom attached button js-button';
    btn.innerHTML = '<i class="add icon"></i><span>Add to playlist</span>';
    
    // Add the event listener
    btn.addEventListener('click', () => {
        console.log('click');
    });

    // Append the button to the created card
    card.appendChild(btn);

    // Add the card to the results
    searchResults.appendChild(card);
    
  });

}

推荐阅读