简体   繁体   中英

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'.

I have trouble attaching event listener to the delete button.

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

    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. 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.

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

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