简体   繁体   中英

Add event listener to button inside template literal

I'm inserting this template literal into a table with a forEach loop. How do I attach an event listener to the button on every iteration?

This just attaches the event listener to the first button in the table:

function renderMenu(doc) {
  const table = `
    <tr data-id=${doc.id}>
        <td>${doc.data().number}</td>
        <td>${doc.data().name}</td>
        <td>${doc.data().ingredients}</td>
        <td>${doc.data().price}</td>
        <td>${doc.data().category}</td>
        <td><button class="btn-remove">Delete</button></td>
    </tr>`

  menu.insertAdjacentHTML('beforeend', table)

  let removeBtn = document.querySelector('.btn-remove')

  //Delete items
  removeBtn.addEventListener('click', (e) => {
      e.preventDefault()
      ...
  })
}

What you could do is add a data- attribute to your button:

`... <button data-remove-button-id="${doc.id}"> ...`

and target it with:

document.querySelector(`[data-remove-button-id="${doc.id}"]`);

Demo (I took some liberty to rename a few things):

 const table = document.querySelector('[data-my-table]'); function addDoc(doc) { const row = ` <tr data-id=${doc.id}> <td>${doc.number}</td> <td>${doc.name}</td> <td>${doc.ingredients}</td> <td>${doc.price}</td> <td>${doc.category}</td> <td><button data-remove-button-id="${doc.id}" class="btn-remove">Delete</button></td> </tr>`; table.insertAdjacentHTML('beforeend', row); const removeBtn = document.querySelector(`[data-remove-button-id="${doc.id}"]`); removeBtn.addEventListener('click', e => { console.log(`deleted row ${e.target.dataset.removeButtonId}`); }); } addDoc({id: 1, number: 1, name: 'foo', ingredients: 'salt', price: 8.5, category: 'food'}); addDoc({id: 2, number: 2, name: 'foo', ingredients: 'salt', price: 8.5, category: 'food'}); addDoc({id: 3, number: 3, name: 'foo', ingredients: 'salt', price: 8.5, category: 'food'}); 
 <table data-my-table></table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM