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

时间:2019-02-14 15:20:51

标签: javascript addeventlistener

我想在点击的订单按钮上使用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);
}));

1 个答案:

答案 0 :(得分:1)

为什么不将事件处理程序直接绑定到按钮?这样,您根本不需要在事件处理程序中检查类:

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>