javascript - 向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 但没有任何效果(可能是因为我做错了)。任何帮助,将不胜感激。我正在失去理智。
解决方案
您可以通过使用“事件委托”来实现这一点,您可以在一个元素上仅设置一个处理程序,该元素是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>
推荐阅读
- sql - KDB 的 Case When 语句
- javascript - TypeError: undefined is not an object (evalating 'ctx.item.Street') (NativeScript)
- javascript - 将平面结构转换为按属性排序的分层结构
- c# - 如何更新多个表中的单个记录?
- sql - 对于第 1 列中的每个值,根据第 2 列中的最大值获取第 3 列的值
- r - 如何对数值向量中的值进行分组和汇总
- javascript - 如何将复选框开关中的值发送到 MySQL 数据库
- javascript - 如何删除不包含任何字符串的行?角
- git - 如何将本地和远程 git 存储库恢复到以前的提交?
- ruby-on-rails - 如何使用设计编辑创建 registrations_controller 操作?