You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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标签中剥离:

  1. 先删除select标签上的onchange="priceStore()"属性
  2. 替换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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 00:06:05