【发布时间】:2022-11-15 05:29:28
【问题描述】:
在我们的商店中,我编写了一个脚本,如果客户购买了 13 件有效商品中的 1 件,另一件商品 (y) 将自动添加到他们的购物车并免费提供。我遇到的问题是,每次客户从他们的购物车中删除该免费商品时,购物车模板页面都会重新加载并重新运行我的脚本,该脚本会自动将该免费商品添加回客户购物车。
我的目标是,尽管我们自动处理将“免费商品”添加到购物车的过程,但客户仍然可以选择删除它,甚至增加它的数量,尽管只有一个仍然是免费的。
附件是我执行上述代码的JS:
{% 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()”函数,但它阻止了整个代码的工作和删除了自动添加免费项目的能力。
【问题讨论】:
标签: javascript shopify preventdefault