首页 > 解决方案 > Javascript - Issue on event listeners of classList

问题描述

I have a "+" button that , when clicked, triggers the creation of a block with an input and 2 buttons, one for validating the input and one for removing it.

enter image description here

// My code looks almost like this :

    addBtn.addEventListener('click', e => {
        addClick++;

// All the elements of the same line (input and 2 buttons) have an int in common in their id string ==> addClick 

// I'm missing all the declarations of the variables here
    blockDiv.appendChild(posteInput);
    blockDiv.appendChild(validateBtn);
    blockDiv.appendChild(deleteBtn);
    globalPostesBlock.appendChild(blockDiv)

    let allDeleteBtn = document.getElementsByClassName('delete-button');

        for (let i = 0; i < allDeleteBtn.length; i++) {

            allDeleteBtn[i].addEventListener('click', e => {

                    // Retrieving the block with the same id
                    let deleteBtnId = parseInt((allDeleteBtn[i].getAttribute('id').match(/\d+/g)).toString());
                    let singlePosteBlock = document.getElementById(`poste-block-${deleteBtnId}`);
                    singlePosteBlock.remove();
                }

            })
        }

The event listener represents the action of clicking the delete button so it can remove its entire containing block

I have the same logic for the validate button, but I'm using ajax in it.

Each time I create a new block, I want to create an event listener associated to this block, but all I found so far is an event listener with a loop on every buttons, so what happens is that the action triggers as many time as the block numbers because of the loop, but I don't know how to dissociate every event listeners.

If I have 3 blocks and I validate one input value which is being inserted in the DB afterwards, the value is being inserted 3 times.

标签: javascript

解决方案


Does this help ?

//id pool
let latestId = 0;

//retrive the button
var myButton = document.querySelector("button");

myButton.addEventListener("click", createKids);

//function declaration :: createKids
function createKids() {
  latestId++;
  //declare and initialization
  let div = document.createElement("div");
  let input = document.createElement("input");
  let buttonSend = document.createElement("button");
  let buttonDelete = document.createElement("button");

  //append input & buttons to div
  div.appendChild(input);
  div.appendChild(buttonSend);
  div.appendChild(buttonDelete);

  //Some beautifying
  buttonSend.innerText = "Send me";
  buttonDelete.innerText = "Delete me";

  //some logic
  div.dataset.id = latestId;

  //event handeling
  buttonSend.addEventListener("click", sendItem);
  buttonDelete.addEventListener("click", deleteItem);

  //insert div
  document.body.appendChild(div);
}

function sendItem(event) {
  //do action and delete ?
  let input = event.target.parentNode.querySelector("input");


  //retrive data
  let val = input.value;
  let id = event.target.parentNode.dataset.id;
  
  //disable input for fun ^^
  input.disabled = true;
  
  //console istead of send 
  console.log(id,val);

  //handle some more
  setTimeout(() => {
    event.target.parentNode.remove();
  }, 3000);
}

function deleteItem(event) {
  event.currentTarget.parentNode.remove();
}
<p>Does this help?</p>
<button>Magic Button</button>


推荐阅读