javascript - 将EventListener 添加到innerHTML

标签 javascript html dom addeventlistener

我是 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>
fiddle :https://jsfiddle.net/y73bstju/7/
但它只会将事件添加到最后一张卡片

最佳答案

它可能有助于创建元素而不是附加 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);
    
  });

}

关于javascript - 将EventListener 添加到innerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63204750/

相关文章:

javascript - AS2 到 AS3 转换错误

javascript - 如何删除jsTreeR中用户折叠指定父节点的选项?

html - CSS Float 左移到页面居中的 Div

php - 我如何搜索(在数据库行中)

javascript - JavaScript 如何创建与 DOM 元素的单向数据绑定(bind)?

javascript - 如何确保 DOM 元素在包含 Flash 对象时触发鼠标悬停

java - DOM 创建带有无效字符的 XML

javascript - 停止传播和开始传播

javascript - Firebug 分析问题 : "no activity to profile"

javascript - 如何在不使用 JavaScript 的情况下最好地重定向网页?