购物车买赠脚本问题:如何避免移除赠品后脚本自动重加
买赠脚本问题与优化方案
问题背景
为店铺开发买赠脚本:顾客购买13种指定商品中任意一款时,系统自动将赠品Y添加到购物车并设为免费。当前问题:顾客移除赠品后,cart-template页面重载会重新执行脚本,导致赠品被再次自动添加。
需求:保留自动添加赠品功能,同时允许顾客自主移除赠品、增加赠品数量(仅1件免费)。
现有实现代码
{% assign liveCode = "yes" %} {% assign bootmodeList = "3932518121587,6631396442197,3957106442355,2017147617395,1658735951987,1561223331955,1561223430259,4810721853525,1658760495219,1561223397491,4698621739093,1658762166387,4760306810965" | split : ',' %} {% assign product_to_add_auto = all_products['test-test-test-enet-cable-bootmod3-flashing-and-f-series-and-g-series-coding-cable'] %} {% assign start = "2022-10-18" | date: '%s' %} {% assign end = "2022-10-19" | date: '%s' %} {% assign today = "now" | date: '%s' %} {% if start <= today and today <= end %} {% unless cart.item_count == 0 or product_to_add_auto.empty? or product_to_add_auto.variants.first.available == false %} {% assign variant_id = product_to_add_auto.variants.first.id %} {% if liveCode == "yes" %} {% if product_to_add_auto.available == true %} {% assign isProduct = false %} {% for item in cart.items %} {% assign product_id = item.product_id | append:"" %} {% if bootmodeList contains product_id %} {% assign isProduct = true %} {% endif %} {% endfor %} {% if isProduct == true %} {{ product_to_add_auto | json }} <script> (function(jquery) { let cartItems = {{ cart.items | json }}, qtyInTheCart = 0, cartUpdates = {}; console.log(cartItems); for (let i = 0; i < cartItems.length; i++) { if (cartItems[i].id === {{ variant_id }}) { qtyInTheCart = cartItems[i].quantity; break; // this checks the cart to prevent double addition of wifi adapter } } if ((cartItems.length === 1) && (qtyInTheCart > 0)) { cartUpdates = { {{ variant_id }}: 0 } // if wifi adapter is already in cart by itself without bootmode, remove it. } else if ((cartItems.length >= 1) && (qtyInTheCart !== 1)) { cartUpdates = { {{ variant_id }}: 1 } // adds wifi adapter to cart if bootmode is in cart and theres not one already } else { return; // if none are true, code doesnt run "catch all" } // http response object const params = { type: 'POST', url: '/cart/update.js', data: { updates: cartUpdates }, dataType: 'json', success: function(stuff) { window.location.href = '/cart'; // reloads to cart on successful post request } }; jquery.ajax(params); // fires ajax request using jquery })(jQuery); </script> {% endif %} {% endif %} {% endif %} {% endunless %} {% endif %}
尝试过的无效方案
在购物车移除按钮上添加唯一ID和事件监听器,使用preventDefault()方法,导致整个脚本失效,无法自动添加赠品。
优化解决方案
核心思路:通过标记用户主动操作,避免脚本重载后重复执行添加逻辑,同时保留赠品数量调整的灵活性。
1. 记录用户主动移除赠品的操作
在cart-template页面添加脚本,不阻止默认移除行为,仅通过localStorage标记用户主动移除了赠品:
jQuery(document).on('click', '.cart__remove-button', function() { const itemId = jQuery(this).data('item-id'); if (itemId === {{ variant_id }}) { localStorage.setItem('userRemovedFreeGift', 'true'); } });
2. 修改原脚本逻辑,读取标记控制添加行为
在原脚本的判断逻辑中加入localStorage标记检查,仅在用户未主动移除时执行自动添加:
{% if isProduct == true %} {{ product_to_add_auto | json }} <script> (function(jquery) { const userRemovedGift = localStorage.getItem('userRemovedFreeGift') === 'true'; let cartItems = {{ cart.items | json }}, qtyInTheCart = 0, cartUpdates = {}; // 用户未主动移除时,执行原有自动添加逻辑 if (!userRemovedGift) { for (let i = 0; i < cartItems.length; i++) { if (cartItems[i].id === {{ variant_id }}) { qtyInTheCart = cartItems[i].quantity; break; } } if ((cartItems.length === 1) && (qtyInTheCart > 0)) { cartUpdates = { {{ variant_id }}: 0 }; } else if ((cartItems.length >= 1) && (qtyInTheCart !== 1)) { cartUpdates = { {{ variant_id }}: 1 }; } else { return; } const params = { type: 'POST', url: '/cart/update.js', data: { updates: cartUpdates }, dataType: 'json', success: function(stuff) { window.location.href = '/cart'; } }; jquery.ajax(params); } else { // 用户主动移除后,若购物车无指定商品,清除标记恢复自动添加 let hasTargetProduct = false; for (let item of cartItems) { {% for product_id in bootmodeList %} if (item.product_id == {{ product_id }}) { hasTargetProduct = true; break; } {% endfor %} } if (!hasTargetProduct) { localStorage.removeItem('userRemovedFreeGift'); } } })(jQuery); </script> {% endif %}
3. 处理赠品数量调整的价格逻辑
允许用户增加赠品数量,仅1件免费,前端显示对应价格:
{% for item in cart.items %} {% if item.variant.id == variant_id %} {% if item.quantity == 1 %} <span class="price">$0.00</span> {% else %} <span class="price">{{ item.variant.price | money }} × {{ item.quantity - 1 }} + $0.00</span> {% endif %} {% else %} <span class="price">{{ item.line_price | money }}</span> {% endif %} {% endfor %}
注意:前端价格仅为用户体验,必须配合后端验证确保仅1件赠品免费,防止恶意篡改。
内容的提问来源于stack exchange,提问作者Ryan Meza
相关产品推荐
相关产品推荐

