首页 > 解决方案 > 向js中的多个选择元素添加事件监听器

问题描述

我有不同的选择元素来改变不同产品的尺寸,每个尺寸都有不同的价格。我可以使用 querySelector 对一个选择元素执行此操作,但它不适用于 querySelectorAll。

这是我仅更改一个选择元素的代码:

const price = document.querySelector(".price");
const select = document.querySelector(".select");

select.addEventListener("change", () => {
  price.innerText = select.options[select.selectedIndex].value;
});
<div>
  <p class="price">$15</p>
  <select class="select">
    <option disabled hidden selected>size</option>
    <option value="$20">40cmx40cm</option>
    <option value="$30">30cmx40cm</option>
    <option value="$50">50cmx50cm</option>
  </select>
</div>

我已经尝试过 for 循环和 forEach 但没有任何效果(可能是因为我做错了)。任何帮助,将不胜感激。我正在失去理智。

标签: javascripthtmlhtml-selectselectedindex

解决方案


您可以通过使用“事件委托”来实现这一点,您可以在一个元素上仅设置一个处理程序,该元素是select您希望处理事件的所有元素的共同祖先。该事件将起源于select但不在那里处理,并将“冒泡”到您选择的祖先。然后,您在该祖先处处理事件,并使用event.target处理程序中可访问的事件来引用触发事件的实际元素,并使用相对 DOM 引用来引用p您需要更新的元素。

这样做的好处是您只需设置一个处理程序(节省内存和性能)并且代码被简化。此外,您可以添加新select结构,而无需更改处理代码。

// Set up a single handler at a common ancestor of all the select elements
document.body.addEventListener("change", function(event){
  // event.target references the element that actually triggered the event
  // Check to see if the event was triggered by a DOM element you care to handle
  if(event.target.classList.contains("select")){
    // Access the <p> element that is the previous sibling to the 
    // select that triggered the event and update it
    event.target.previousElementSibling.textContent = event.target.value
  }
});
<div>
  <p class="price">$15</p>
  <select class="select">
    <option disabled hidden selected>size</option>
    <option value="$20">40cmx40cm</option>
    <option value="$30">30cmx40cm</option>
    <option value="$50">50cmx50cm</option>
  </select>
</div>
<div>
  <p class="price">$15</p>
  <select class="select">
    <option disabled hidden selected>size</option>
    <option value="$20">40cmx40cm</option>
    <option value="$30">30cmx40cm</option>
    <option value="$50">50cmx50cm</option>
  </select>
</div>
<div>
  <p class="price">$15</p>
  <select class="select">
    <option disabled hidden selected>size</option>
    <option value="$20">40cmx40cm</option>
    <option value="$30">30cmx40cm</option>
    <option value="$50">50cmx50cm</option>
  </select>
</div>


推荐阅读