我需要根据购买的主要商品数量来更改免费商品的数量。我们卖剃须刀。目前,当您购买剃须刀时,我们会添加免费礼品。这个礼品是10个免费刀片。我遇到的问题是如果你买2把剃须刀,你仍然只能得到1件免费礼品。我需要根据他们购买的剃须刀数量更改免费礼品的隐藏输入字段中的数量值。这是代码:
这部分代码会检查Razor的购物车,如果它在那里它设置为true,它会抓住购买的剃须刀数量:
{% if item.product.tags contains '10bladesfree' %}
{% assign free10blades = true %}
{% assign razor_count = item.quantity %}
{% endif %}
这部分代码循环通过购物车,如果剃须刀在购物车中,则会添加免费礼品。如果剃须刀不在购物车中,则会删除免费礼物:
{% if free10blades %}
<script>
if (typeof Shopify === 'undefined') var Shopify = {};
Shopify.cart = {{ cart | json }};
Shopify.toAdd = {{ linklistfree10blades.links.first.object.variants.first.id }};
var pleaseAdd10Blades = false;
Shopify.idsInCart = [];
for (var i=0; i<Shopify.cart.items.length; i++) {
Shopify.idsInCart.push(Shopify.cart.items[i].id);
if (Shopify.cart.items[i].id !== Shopify.toAdd) {
//console.log('add bouns item');
pleaseAdd10Blades = true;
}
}
if (pleaseAdd10Blades && (jQuery.inArray(Shopify.toAdd, Shopify.idsInCart) === -1)) {
var params = {
type: 'POST',
url: '/cart/add.js',
data: 'quantity=' + {{ razor_count }} + '&id=' + Shopify.toAdd,
dataType: 'json',
success: function(line_item) {
window.location.href = '/cart';
}
};
jQuery.ajax(params);
}
</script>
{% else %}
<script>
if (typeof Shopify === 'undefined') var Shopify = {};
Shopify.cart = {{ cart | json }};
Shopify.toAdd = {{linklistfree10blades.links.first.object.variants.first.id }};
var pleaseRemove10Blades = false;
Shopify.idsInCart = [];
for (var i=0; i<Shopify.cart.items.length; i++) {
Shopify.idsInCart.push(Shopify.cart.items[i].id);
if (Shopify.cart.items[i].id === Shopify.toAdd) {
pleaseRemove10Blades = true;
}
}
if (pleaseRemove10Blades) {
var params = {
type: 'POST',
url: '/cart/update.js',
data: 'updates[' + Shopify.toAdd + ']=0',
dataType: 'json',
success: function(line_item) {
window.location.href = '/cart';
}
};
jQuery.ajax(params);
}
</script>
{% endif %}
我还在页面顶部有这个代码来为免费礼物创建隐藏的输入字段:
{% if item.product.tags contains 'free-10-blades'%}
<input type="hidden" name="updates[]" id="updates_{{ item.id }}" value="{{ item.quantity }}" min="0" data-id="{{ item.id }}">
{% else %}