select下拉框onchange事件仅修改首个product元素价格的问题求解
问题根因
你在遍历.product元素的循环中,直接通过document.getElementsByClassName全局查找价格元素,取索引[0]永远匹配页面中第一个对应类名的价格节点,因此只会修改第一个商品的价格显示状态,其余商品不会生效。
修复方案
原生JS优化版
修改逻辑为从当前遍历到的商品节点下查找对应价格元素,同时优化重复代码:
function priceStore(){ const option = document.getElementById("Store").value; const productList = document.querySelectorAll(".product"); let showPriceClass = ''; // 匹配对应要显示的价格类 if(option === "Store1" || option === "Store3") { showPriceClass = 'price1'; } else if(option === "Store2" || option === "Store4" || option === "Store5") { showPriceClass = 'price2'; } else if(option === "Store6") { showPriceClass = 'price3'; } // 遍历所有商品修改显示状态 productList.forEach(product => { // 先隐藏当前商品下所有价格 product.querySelectorAll('[class^="price"]').forEach(price => { price.style.display = 'none'; }); // 显示目标价格 product.querySelector(`.${showPriceClass}`).style.display = 'block'; }); }
jQuery简化版
因为页面已经引入jQuery,可以用更简洁的写法实现,同时可以把事件绑定从HTML标签中剥离:
- 先删除select标签上的
onchange="priceStore()"属性 - 替换JS代码为以下内容:
$(function(){ // 绑定下拉框change事件 $('#Store').on('change', function(){ const option = $(this).val(); let showPriceClass = ''; if(option === "Store1" || option === "Store3") { showPriceClass = '.price1'; } else if(option === "Store2" || option === "Store4" || option === "Store5") { showPriceClass = '.price2'; } else if(option === "Store6") { showPriceClass = '.price3'; } // 批量修改所有商品的价格显示 $('.product').find('[class^="price"]').hide().end().find(showPriceClass).show(); }) })
HTML冗余修正
原select下拉框中Store4、Store5、Store6的显示文本错误,建议修正为:
<option value="Store4">Store4</option> <option value="Store5">Store5</option> <option value="Store6">Store6</option>
内容的提问来源于stack exchange,提问作者Pirelli
相关产品推荐
相关产品推荐

