[英]How to add addEventListener on particular clicked button?
我想在單擊的訂單按鈕上使用addEventListener()
。 最有效的方法是什么? 這是我現在的做法:
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回答了我在尋找什么:
const pizzaButtons = document.querySelectorAll('.order-button');
pizzaButtons.forEach(button => button.addEventListener('click', event => {
updateOrderSummary(event);
}));
為什么不將事件處理程序直接綁定到按鈕? 這樣,您根本不需要在事件處理程序中檢查類:
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.