简体   繁体   English

将 eventListener 附加到单击另一个按钮时将出现的按钮?

[英]attaching an eventListener to a button that will appear when clicking another button?

so basically, I'm working on a to-do list and you have to enter a task with the button 'enter' then the task appears in the UI with a button called 'delete'.所以基本上,我正在处理一个待办事项列表,您必须使用“输入”按钮输入一个任务,然后该任务会出现在 UI 中,并带有一个名为“删除”的按钮。

I have trouble attaching event listener to the delete button.我无法将事件侦听器附加到删除按钮。

HTML: HTML:

<div id="container">

    <input type="checkbox" id="checkbox" name="task1"  >
    <label for="task1" id="tasks">running 10 mile</label><br>
    <button class="delete">Delete</button>
    
</div>

That's the default one.这是默认的。

'''javascript '''javascript

    tasks = []

    btnEnter.addEventListener('click',function(e){
    e.preventDefault();
    
    if (labelInput.value !== ''){
        tasks.push(labelInput.value)//if not '' push to the tasks arr

    // to display the last element of the tasks array:
    tasks.slice(-1).map((task , i)=>{
    
    const html =
    `<div id="container">
    <input type="checkbox" id="checkbox" name="task${i}"  >
    <label for="task${i}" id="tasks">${task}</label><br>
    <button class="delete">Delete</button>
    </div>`;
    inputDiv.insertAdjacentHTML('afterend',html)

    // to clear the input text;
    labelInput.value ='';   
})

    }else {alert('enter a valid task')};
    
})

The problem with attaching an event listener on each of the delete buttons is they don't exist in the DOM when the page first loads.在每个删除按钮上附加事件侦听器的问题是,当页面首次加载时,它们在 DOM 中不存在。 We'll need to attach the event listener on an ancestor of the task items.我们需要将事件侦听器附加到任务项的祖先上。 We can use the div#container as the ancestor and insert every new task inside.我们可以使用div#container作为祖先并将每个新任务插入其中。

  const container = document.querySelector('div#container')

  const html = `
    <div>
      <input type="checkbox" id="task${i}" name="task${i}">
      <label for="task${i}">${task}</label><br>
      <button class="delete">Delete</button>
    </div>
  `
  container.insertAdjacentHTML('afterbegin', html)

And we can attach the one click listener on the container which will delegate the event to any new delete buttons that will be clicked.我们可以在容器上附加一个单击监听器,它将事件委托给任何将被单击的新删除按钮。

  container.addEventListener('click', e => {
    document.querySelectorAll('button.delete').forEach(button => {
      if (button.contains(e.target)) {
        // ...delete the task item
      }
    })
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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