将事件侦听器添加到模板文字内的按钮

时间:2018-11-30 11:28:53

标签: javascript addeventlistener template-literals

我正在将此模板文本插入具有forEach循环的表中。如何在每次迭代中将事件侦听器附加到按钮上?

这只是将事件侦听器附加到表中的第一个按钮:

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()
      ...
  })
}

1 个答案:

答案 0 :(得分:1)

您可以做的是向按钮添加data-属性:

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

并将其定位为:

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

演示(我可以自由命名一些东西):

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>