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

基于if/else条件通过JS控制div内商品推荐价格的展示规则

价格展示逻辑实现方案

现有代码问题

  1. 调用getElementsByClassName("rec_price_num")未指定父级为当前遍历的商品容器,会全局查找元素,循环取值时会出现匹配错误
  2. 仅做了变量取值操作,没有实现元素显隐、删除线样式控制的核心逻辑
  3. 存在大量重复的变量声明与取值代码,冗余度高

完整实现代码

新增CSS样式(可选,用于统一控制样式)

/* 原价删除线样式 */
.rec_price_num.del {
  text-decoration: line-through;
  color: #666;
  margin-left: 8px;
}
/* 折扣价高亮样式 */
.dynamic-price {
  color: #e53935;
  font-weight: 700;
  display: inline-block;
}

完善后的JS代码

// 等待DOM完全渲染后执行,避免获取元素失败
document.addEventListener('DOMContentLoaded', function() {
  // 获取所有商品的价格容器
  const itemPrices = document.querySelectorAll('.slider-wrapper .pricebox');
  
  for (let i = 0; i < itemPrices.length; i++) {
    const currentPriceBox = itemPrices[i];
    // 在当前商品容器内查找对应价格元素,避免跨商品匹配
    const discountEl = currentPriceBox.querySelector('.dynamic-price');
    const regularEl = currentPriceBox.querySelector('.rec_price_num');
    
    // 清理折扣价前后空格,判断是否为有效值
    const discountValue = discountEl.innerHTML.trim();
    
    if (discountValue && discountValue !== 'null') {
      // 存在有效折扣价:展示两个价格,原价添加删除线
      regularEl.classList.add('del');
      discountEl.style.display = 'inline-block';
    } else {
      // 无有效折扣价:隐藏折扣价,原价去掉删除线
      discountEl.style.display = 'none';
      regularEl.classList.remove('del');
    }
  }
})

补充说明

如果不想额外添加CSS类,可直接在JS中控制原价样式,将regularEl.classList.add('del')替换为regularEl.style.textDecoration = 'line-through',regularEl.classList.remove('del')替换为regularEl.style.textDecoration = 'none'即可。

如果平台模板渲染空的${discountvalue}时输出的是其他占位符,可自行调整判断条件匹配对应规则。

内容的提问来源于stack exchange,提问作者Mr.Devops

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:45:05