我有不同的选择元素来更改不同产品的尺寸,每种尺寸都有不同的价格。我可以使用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
let target = event.target;
// Check to see if the event was triggered by a DOM element
// you care to handle
if(target.classList.contains("select")){
// Access the <p> element that is the previous sibling to the
// select that triggered the event and update it
target.previousElementSibling.textContent = 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句