简体   繁体   English

如何在特定单击的按钮上添加addEventListener?

[英]How to add addEventListener on particular clicked button?

I want to use addEventListener() on the clicked order button. 我想在单击的订单按钮上使用addEventListener() What is the most efficient way of doing it? 最有效的方法是什么? Here's how I'm doing it now: 这是我现在的做法:

 const executeUpdateSummary = (e) => { const classNameOfTargetedEl = event.target.className; if (classNameOfTargetedEl === ('order-button button')) { updateOrderSummary(e); } }; const pizzasElement = document.querySelector('.pizzas'); pizzasElement.addEventListener('click', executeUpdateSummary, false); 
 <div class="pizzas"> <div class="menu-item"> <div class="name"> Margherita </div> <div class="price">Price: $5</div> <div class="toppings">Toppings: tomato mozzarella </div> <button class="order-button button" type="button">Add to order</button> </div> <div class="menu-item"> <!-- There are multiple menu-items --> </div> </div> 

@MTCoster's answered what I was looking for: @MTCoster回答了我在寻找什么:

const pizzaButtons = document.querySelectorAll('.order-button');

pizzaButtons.forEach(button => button.addEventListener('click', event => {
    updateOrderSummary(event);
}));

Why not bind the event handler directly to the buttons? 为什么不将事件处理程序直接绑定到按钮? That way you don't need to check the class in the event handler at all: 这样,您根本不需要在事件处理程序中检查类:

 const pizzaButtons = Array.from(document.querySelectorAll('.pizzas .order-button')); pizzaButtons.forEach(btn => btn.addEventListener('click', event => { console.log('Updating order summary...'); console.log('Clicked button:', event.target); })); 
 <div class="pizzas"> <div class="menu-item"> <div class="name"> Margherita </div> <div class="price">Price: $5</div> <div class="toppings">Toppings: tomato mozzarella </div> <button class="order-button button" type="button">Add to order</button> </div><div class="menu-item"> <div class="name"> Pepperoni </div> <div class="price">Price: $7</div> <div class="toppings">Toppings: tomato mozzarella pepperoni </div> <button class="order-button button" type="button">Add to order</button> </div> </div> 

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

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