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

当售价与常规价格相同时,如何隐藏常规价格显示

解决促销价与常规价相同时隐藏删除线价格的问题

一、模板层面处理(推荐)

你用的是Handlebars模板,直接在模板里判断两个价格是否相等,只在不等时渲染删除线价格,这比JS后处理更高效,还能避免不必要的DOM生成。

修改模板代码:

{{#if attributes.price.value}}
<p class="pr__price">
   <span class="pr__price--active">
     <span data-locale="en_US" data-currencycode="USD">$</span> 
     {{attributes.price.value}}
   </span>

   {{#if attributes.listPrice.value}}
     {{#ifCond attributes.listPrice.value '!==' attributes.price.value}}
     <span class="pr__price--inactive">
       <span data-locale="en_US" data-currencycode="USD">$</span> 
       {{attributes.listPrice.value}}
     </span>
     {{/ifCond}}
   {{/if}}
</p>
{{/if}}

Handlebars默认没有比较判断的助手,需要注册一个ifCond助手函数:

Handlebars.registerHelper('ifCond', function(v1, operator, v2, options) {
  switch (operator) {
    case '==':
      return (v1 == v2) ? options.fn(this) : options.inverse(this);
    case '===':
      return (v1 === v2) ? options.fn(this) : options.inverse(this);
    case '!=':
      return (v1 != v2) ? options.fn(this) : options.inverse(this);
    case '!==':
      return (v1 !== v2) ? options.fn(this) : options.inverse(this);
    case '<':
      return (v1 < v2) ? options.fn(this) : options.inverse(this);
    case '<=':
      return (v1 <= v2) ? options.fn(this) : options.inverse(this);
    case '>':
      return (v1 > v2) ? options.fn(this) : options.inverse(this);
    case '>=':
      return (v1 >= v2) ? options.fn(this) : options.inverse(this);
    case '&&':
      return (v1 && v2) ? options.fn(this) : options.inverse(this);
    case '||':
      return (v1 || v2) ? options.fn(this) : options.inverse(this);
    default:
      return options.inverse(this);
  }
});

二、JavaScript层面修复(无法修改模板时用)

你之前的JS代码有两个关键问题:

  1. const声明的变量不能重新赋值,而且你写的regularPrice === null是比较操作,不是赋值,就算改成=也只是改变变量值,不会影响DOM显示;
  2. 没有操作DOM元素本身,只是修改了变量,页面自然不会有变化。

修改后的JS代码:

// 先获取元素,避免找不到时报错
const regularPriceEl = document.querySelector("span.pr__price--inactive");
const salePriceEl = document.querySelector("span.pr__price--active");

if (regularPriceEl && salePriceEl) {
  // 去掉文本前后的空格,防止空格导致判断失误
  const regularPrice = regularPriceEl.textContent.trim();
  const salePrice = salePriceEl.textContent.trim();
  
  if (regularPrice === salePrice) {
    // 隐藏删除线价格元素
    regularPriceEl.style.display = 'none';
    // 或者直接删除元素:regularPriceEl.remove();
  }
}

内容的提问来源于stack exchange,提问作者SuperSako22

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:05:31