简体   繁体   中英

EventListener doesn't trigger by clicking to div's

I create multiple div's dynamically with Javascript

var cart = document.createElement("div");
cart.classList.add("buy-item");
cart.setAttribute("name", "buy-food"); 
div.appendChild(cart);

and when i collect all the elements with the "buy-item" class i get the elements as an HTMLCollection but when i want to know when it was clicked nothing happens

var elements = document.getElementsByClassName("buy-item");
console.log(elements)

function addFoodToCart() {
    console.log("One of buy-item class itemes was clicked")
};

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', addFoodToCart);
}

The HTML element looks like this

<div class="food-wrap dynamic-food">
 <img class="food-item-img" src="/img/foodItem.png">
 <p class="food-title">Csípős</p><p class="food-price">190</p>
 <div class="buy-item" name="buy-food"></div>
 <div class="tooltip">
  <span class="tooltiptext">Csípős szósz</span>
 </div>
</div>

tl;dr: Add the event listener to the parent div (the one holding all the other elements that you have/will be creating) and use event.target to know which one was clicked.

Not sure if this helps and if this is your case, but you could be benefited by the understanding of Event Bubbling and Event Delegation in Javascript.

In my example below, run the code and click in each paragraph. The console log will show which element you cliked.

 function findTheOneClicked(event) { console.log(event.target) } const mainDiv = document.getElementById("parent"); mainDiv.addEventListener('click', findTheOneClicked);
 <div id="parent"> <p>"Test 1"</p> <p>"Test 2"</p> <p>"Test 3"</p> </div>

This is really good when you have an element with many other elements on it and you want to do something with them, or when you want to add an event handler to an element that is not available (not created yet) on your page.

Good reading on this topic: https://javascript.info/bubbling-and-capturing

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