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

Shopify购物车页面:实现商品数量/总价变化时实时更新提示信息

Shopify购物车提示信息实时更新方案

方案一:无需刷新页面实时更新(推荐)

该方案通过监听Shopify购物车变化事件,动态修改提示区域内容,避免页面刷新带来的体验损耗。

步骤1:调整HTML结构

给提示区域添加固定ID,方便JS定位,同时保留Liquid代码作为初始渲染内容:

<div id="gift-prompt" class="yellow-area">
  {% if cart.item_count == 0 %}
    <p>FREE Gift Over <span>SAR 1000</span></p>
  {% endif %}
  {% if cart.item_count > 99 %}
    <p>Congratulations! You've got FREE GIFT</p>
  {% endif %}
  {% if cart.item_count < 8 and cart.item_count > 0 %}
    <p>Congratulations! You've got FREE GIFT</p>
  {% elsif cart.item_count < 19 and cart.item_count >= 8 %}
    <p>Congratulations! You've got FREE GIFT</p>
  {% endif %}
</div>

步骤2:编写JS逻辑

定义生成提示文本的函数,并监听购物车更新事件:

// 根据购物车数据生成提示内容
function updateGiftPrompt(cart) {
  const promptContainer = document.getElementById('gift-prompt');
  if (!promptContainer) return;

  let promptContent = '';
  const itemCount = cart.item_count;

  if (itemCount === 0) {
    promptContent = '<p>FREE Gift Over <span>SAR 1000</span></p>';
  } else if (itemCount > 99) {
    promptContent = '<p>Congratulations! You\'ve got FREE GIFT</p>';
  } else if (itemCount > 0 && itemCount < 8) {
    promptContent = '<p>Congratulations! You\'ve got FREE GIFT</p>';
  } else if (itemCount >= 8 && itemCount < 19) {
    promptContent = '<p>Congratulations! You\'ve got FREE GIFT</p>';
  }

  promptContainer.innerHTML = promptContent;
}

// 页面加载时初始化提示内容
document.addEventListener('DOMContentLoaded', () => {
  Shopify.API.getCart().then(cart => {
    updateGiftPrompt(cart);
  });
});

// 监听购物车更新事件,实时更新提示
document.addEventListener('cart:updated', (event) => {
  const latestCart = event.detail.cart;
  updateGiftPrompt(latestCart);
});

补充说明

  • 多数Shopify主题会自动触发cart:updated事件,若你的主题无此机制,需在自定义购物车操作(如添加商品、修改数量的按钮点击事件)中,手动调用Shopify API获取最新购物车数据,再执行updateGiftPrompt函数。
  • 若需根据总价判断,只需将cart.item_count替换为cart.total_price(注意单位为分,例如SAR 1000对应数值100000)。

方案二:购物车变化时自动刷新页面(不推荐)

该方案实现简单,但会打断用户操作流程,体验较差,仅作备选:

// 监听购物车更新事件,触发页面刷新
document.addEventListener('cart:updated', () => {
  window.location.reload();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:35:21