【问题标题】:Shopify cart page - Changing quantity input value with jQueryShopify 购物车页面 - 使用 jQuery 更改数量输入值
【发布时间】:2020-12-24 04:24:28
【问题描述】:

我在购物车布局中有 + 和 - 按钮,它们正在使用 jQuery 更改数量输入的值。

它在页面和源代码中完美运行(数量值更改),但在页面刷新后它不起作用,并且不会反映在结帐页面上。

手动更改数量(使用内置输入箭头或在字段中输入新数量)正常工作。

    $(".qty-button").on("click", function() {

    var $button = $(this);
    var oldValue = $button.parent().find("input").val();
    var newVal;

    if ($button.text() === "+") {
        newVal = parseFloat(oldValue) + 1;
    } else {
        if (oldValue > 0) {
            newVal = parseFloat(oldValue) - 1;
        } else {
            newVal = 0;
        }
    }

    $button.parent().find("input").attr('value', newVal).trigger('change');

});

它会更改页面源中的值并反映在购物车页面上,但在功能方面没有任何作用,因为它会在页面刷新或结帐时恢复到原始值。

有什么想法吗?

【问题讨论】:

  • 购物车页面是否有AJAX方式更新购物车或手动更新购物车按钮?
  • 你能分享一下 " 在页面和源代码中完美运行的代码(数量值发生变化),但在页面刷新后它不起作用并且不会反映在结帐页面”?
  • @OnkarSingh 我在购物车页面上没有任何 AJAX。
  • @KarimTarek 我发布的代码正在运行,但正如问题中所述,它仅在视觉上有效,但由于某种原因它并没有真正更新值。 P.s 我还将代码更新为我正在使用的完整 sn-p。

标签: shopify liquid


【解决方案1】:

不知道我需要触发 Shopify Cart API。

如果将来有人需要它,请使用:

  <div class="cart-item-block qty-selector">
      <div class="qty-button increase" onclick="Shopify.addItem({{ item.variant.id }}, this.parentNode.querySelector('input[type=number]').value)">+</div>
      <input id="updates_{{ item.key }}" class="cart-qty-input" type="number"
             name="updates[]" value="{{ item.quantity }}" min="1" pattern="[0-9]*"
             >
      <div class="qty-button decrease" onclick="Shopify.removeItem({{ item.variant.id }}, this.parentNode.querySelector('input[type=number]').value)">-</div>
  </div>

<script>
    Shopify.addItem = async function(id,quantity){
        await $.ajax({
            method:'POST',
            url:'/cart/change.js',
            data:{ id:id, quantity:(++quantity) },
            dataType: 'json'
        })
    };
    
    Shopify.removeItem = async function(id,quantity){
        await $.ajax({
            method:'POST',
            url:'/cart/change.js',
            data:{ id:id, quantity:(--quantity) },
            dataType: 'json'
        })
    };
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多