Shopify购买按钮最小数量

时间:2017-06-21 17:55:46

标签: javascript shopify

我目前正在使用Shopify Buy Button

在大多数情况下,我只是复制并粘贴嵌入代码并没有太大变化。

我有一些产品需要购买5件或更多的产品。

典型的“添加到行李”按钮只会添加一个并在购物车内,按下时会添加/减去一个。

我的问题

  • 单击“添加到购物车”时,有没有办法设置默认数量?
  • 有没有办法在上述项目
  • 上添加默认减去/减去

注意:对于所有项目,我不希望这样,只有嵌入购买代码所针对的特定项目。

我搜索了default compenentsdeveloper section,发现了以下内容:

var events = {
  addVariantToCart: function (product) {},
  updateQuantity: function (product) {},
 ...
}

我认为这可能是我正在寻找的,但我找不到任何有关如何更新所述产品的详细信息。

如果有人能帮助或指导我朝着正确的方向前进,我们将不胜感激。

我的嵌入代码

<div id='product-component-ITEM-ID'></div>
<script type="text/javascript">
/*<![CDATA[*/
(function () {
  var scriptURL = 'https://sdks.shopifycdn.com/buy-button/latest/buy-button-storefront.min.js';
  if (window.ShopifyBuy){if(window.ShopifyBuy.UI){ShopifyBuyInit();}else{loadScript();}}else{loadScript();}
  function loadScript() {var script = document.createElement('script');script.async = true;script.src = scriptURL;(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);script.onload = ShopifyBuyInit;}
  function ShopifyBuyInit() {
    var client = ShopifyBuy.buildClient({domain: 'DOMAIN.myshopify.com',apiKey: 'API-KEY',appId: '6'});
    ShopifyBuy.UI.onReady(client).then(function(ui){ui.createComponent('product',{id:["ITEM-ID"],node:document.getElementById('product-component-{{page.item_id}}'),moneyFormat:'%24%7B%7Bamount%7D%7D',

    options:{
      "product":{
        "variantId":"all",
        "width":"240px",
        "contents":{
          "img":false,
          "imgWithCarousel":false,
          "title":false,
          "variantTitle":false,
          "price":false,
          "description":false,
          "buttonWithQuantity":false,
          "quantity":false
        },
        "text":{
          "button":"ADD TO BAG"
        },
        "styles":{
          "product":{
            "text-align":"left",
            "@media(min-width:601px)":{
              "max-width":"100%",
              "margin-left":"0",
              "margin-bottom":"50px"
            }
          },
          "button":{
            "background-color":"#393a39",
            "font-family":"Lato,sans-serif",
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px",
            "padding-left":"35px",
            "padding-right":"35px",
            ":hover":{
              "background-color":"#333433"
            },
            "border-radius":"0px",
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "title":{
            "font-size":"26px"
          },
          "price":{
            "font-size":"18px"
          },
          "quantityInput":{
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px"
          },
          "compareAt":{
            "font-size":"15px"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "cart":{
        "contents":{
          "button":true
        },
        "styles":{
          "button":{
            "background-color":"#393a39",
            "font-family":"Lato,sans-serif",
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px",
            ":hover":{
              "background-color":"#333433"
            },
            "border-radius":"0px",
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "footer":{
            "background-color":"#ffffff"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "modalProduct":{
        "contents":{
          "img":false,
          "imgWithCarousel":true,
          "variantTitle":false,
          "buttonWithQuantity":true,
          "button":false,
          "quantity":false
        },
        "styles":{
          "product":{
            "@media(min-width:601px)":{
              "max-width":"100%",
              "margin-left":"0px",
              "margin-bottom":"0px"
            }
          },
          "button":{
            "background-color":"#393a39",
            "font-family":"Lato,sans-serif",
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px",
            "padding-left":"35px",
            "padding-right":"35px",
            ":hover":{
              "background-color":"#333433"
            },
            "border-radius":"0px",
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "quantityInput":{
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "toggle":{
        "iframe":false,
        "sticky":false,
        "templates":{
          "icon":'<i class="fa fa-shopping-bag fa-lg darkgrey" aria-hidden="true"></i>'
        },
        "contents":{
          "icon":true,
          "title":false
        },
        "events":{
          afterInit:function (component)      {
            document.getElementById('cart-toggle').appendChild(component.node);
          },

        },
        "order":[
          'count',
          'icon'
        ],
        "styles":{
          "toggle":{
            "font-family":"Lato,sans-serif",
            "background-color":"#393a39",
            ":hover":{
              "background-color":"#333433"
            },
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "count":{
            "font-size":"13px"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "productSet":{
        "styles":{
          "products":{
            "@media(min-width:601px)":{
              "margin-left":"-20px"
            }
          }
        }
      }
    }
    }

    );});}})();
/*]]>*/
</script>

1 个答案:

答案 0 :(得分:4)

经过几个小时的实验,这就是我提出的解决方案。到目前为止,我的测试表明它坚固可靠,但如果您发现任何问题,请告诉我,我会看到我能做些什么。

以下是代码,使用Shopify Buy Button homepage中的示例代码。不幸的是,这不会在一个片段中运行,但是如果你把它放在一个HTML文件中运行它就可以测试它。

完整示例代码

<强> HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id='product-component-05cfb487fb6' data-minqty='5'></div>

<强>使用Javascript:

function ShopifyBuyInit() {
    var client = ShopifyBuy.buildClient({
        domain: 'embeds.myshopify.com',
        apiKey: '952162710f94aa7b7644b14b2a94f4a3',
        appId: '6',
    });

    ShopifyBuy.UI.onReady(client).then(function(ui) {
        ui.createComponent('product', {
            id: [3030475907],
            node: document.getElementById('product-component-05cfb487fb6'),
            moneyFormat: '%24%7B%7Bamount%7D%7D',
            options: {
                "product": {
                    "styles": {
                        "button": {
                            "background-color": "#292929",
                            ":hover": {
                                "background-color": "#464646"
                            },
                            ":focus": {
                                "background-color": "#464646"
                            }
                        },
                    },
                    "events": {
                        "addVariantToCart": function(product) {
                            product.model.selectedQuantity = 1;
                            var minQty = $(product.node).data('minqty');
                            if (product.cart.model.lineItemCount < minQty) {
                                product.updateQuantity(function() {
                                    return minQty - (product.cart.model.lineItemCount);
                                });
                            }
                        }
                    }
                },
                "cart": {
                    "events": {
                        "updateItemQuantity": function(cart) {
                            for (let i = 0; i < ui.components.product.length; i++) {
                                var product = ui.components.product[i];
                                var node = product.node;
                                if ($(node).data('minqty')) {
                                    var minQty = $(node).data('minqty');
                                    setTimeout(function() {
                                        setProductQuantity(node, product, minQty, ui);
                                    }, 1);
                                }
                            }
                        }
                    }
                }
            }
        });
    });
}

function setProductQuantity(node, product, minQty, ui) {
    if (product.cart.model.lineItemCount < minQty && product.cart.model.lineItemCount > 0) {
        $('.shopify-buy-cart-wrapper').find('iframe').contents().find("div[id='" + product.cart.model.lineItems[0].id + "']").find('.shopify-buy__quantity-decrement').click();
    }
}

(function() {
    var scriptURL = 'https://sdks.shopifycdn.com/buy-button/latest/buy-button-storefront.min.js';
    window.ShopifyBuy && window.ShopifyBuy.UI ? ShopifyBuyInit() : loadScript();

    function loadScript() {
        var script = document.createElement('script');
        script.async = true;
        script.src = scriptURL;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);
        script.onload = ShopifyBuyInit;
    }
})();

深入解释

这可以通过收听Shopify购买按钮中的两个事件来实现:addVariantToCartupdateItemQuantity。您要做的第一件事是向产品div添加data-minqty属性。我们稍后会使用该数据属性。

<div id='product-component-05cfb487fb6' data-minqty='5'></div>

单击“添加到购物车”时会触发第一个事件。我们会收听它,以便我们可以将minQty项添加到购物车中(在我们的示例中,这是5)。

"addVariantToCart": function(product) {
    product.model.selectedQuantity = 1;
    var minQty = $(product.node).data('minqty');
    if (product.cart.model.lineItemCount < minQty) {
        product.updateQuantity(function() {
            return minQty - product.cart.model.lineItemCount;
        });
    }
}

这样做首先将所选项目的数量设置为1.这是因为所选数量会自动设置为最后添加的数量,如果我们要将项目添加到购物车中时间会== minQty(即5)。然后我们从之前添加的数据属性中找到最小数量(product.node是产品的div元素)。我们检查数量是否小于minQty,如果是,我们会在产品上运行updateQuantity。出于某种原因,它是相对的,因此我们使用minQtyproduct.cart.model.lineItemCount之间的差异运行它,这是当前的数量。

更改购物车本身的数量时会触发第二个事件。我们会倾听,因此我们可以确保客户无法将数量减少到minQty以下。

"updateItemQuantity": function(cart) {
    for (let i = 0; i < ui.components.product.length; i++) {
        var product = ui.components.product[i];
        var node = product.node;
        if ($(node).data('minqty')) {
            var minQty = $(node).data('minqty');
            setTimeout(function() {
                setProductQuantity(node, product, minQty, ui);
            }, 1);
        }
    }
}

由于我们并不确切地知道购物车中的哪个商品的数量发生了变化,因此我们会仔细检查它们,然后检查它们是否有minQty,如果有的话,是否有&{ #39;在下面。然后我们使用setTimeout,因为在更新数量之前会触发此事件,所以如果我们在此处更改它,它就会被重置。我们称这个函数为:

function setProductQuantity(node, product, minQty, ui) {
    if (product.cart.model.lineItemCount < minQty && product.cart.model.lineItemCount > 0) {
        $('.shopify-buy-cart-wrapper').find('iframe').contents().find("div[id='" + product.cart.model.lineItems[0].id + "']").find('.shopify-buy__quantity-decrement').click();
    }
}

此功能检查新数量是否小于minQty。如果不是,我们什么也不做(让数量正常更新)。如果是,我们想要从购物车中删除该商品。没有&#34;删除&#34;按钮(它通常依赖于将数量降低到0以从购物车中移除),并且由于我们有最小数量,这不可能发生,因此我们需要检查并手动将其删除。我们只是模拟点击&#34;数量减少&#34;按钮。我们只需要执行一次,因为每次执行此操作都会触发updateItemQuantity,因此它会自动循环,直到项目被删除。

与您的代码集成

我无法直接测试您的代码,但我已将更改添加到您的代码中,因此希望您能够弄明白。它确实需要jQuery,因为我不知道足够的原生Javascript来做我需要做的事情。

<div id='product-component-ITEM-ID' data-minqty='5'></div>
<script type="text/javascript">
/*<![CDATA[*/
(function () {
  var scriptURL = 'https://sdks.shopifycdn.com/buy-button/latest/buy-button-storefront.min.js';
  if (window.ShopifyBuy){if(window.ShopifyBuy.UI){ShopifyBuyInit();}else{loadScript();}}else{loadScript();}
  function loadScript() {var script = document.createElement('script');script.async = true;script.src = scriptURL;(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);script.onload = ShopifyBuyInit;}
  function ShopifyBuyInit() {
    var client = ShopifyBuy.buildClient({domain: 'DOMAIN.myshopify.com',apiKey: 'API-KEY',appId: '6'});
    ShopifyBuy.UI.onReady(client).then(function(ui){ui.createComponent('product',{id:["ITEM-ID"],node:document.getElementById('product-component-{{page.item_id}}'),moneyFormat:'%24%7B%7Bamount%7D%7D',

    options:{
      "product":{
        "variantId":"all",
        "width":"240px",
        "contents":{
          "img":false,
          "imgWithCarousel":false,
          "title":false,
          "variantTitle":false,
          "price":false,
          "description":false,
          "buttonWithQuantity":false,
          "quantity":false
        },
        "events": {
          "addVariantToCart": function(product) {
            product.model.selectedQuantity = 1;
            var minQty = $(product.node).data('minqty');
            if (product.cart.model.lineItemCount < minQty) {
              product.updateQuantity(function() {
                return minQty - (product.cart.model.lineItemCount);
              });
            }
          }
        }
        "text":{
          "button":"ADD TO BAG"
        },
        "styles":{
          "product":{
            "text-align":"left",
            "@media(min-width:601px)":{
              "max-width":"100%",
              "margin-left":"0",
              "margin-bottom":"50px"
            }
          },
          "button":{
            "background-color":"#393a39",
            "font-family":"Lato,sans-serif",
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px",
            "padding-left":"35px",
            "padding-right":"35px",
            ":hover":{
              "background-color":"#333433"
            },
            "border-radius":"0px",
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "title":{
            "font-size":"26px"
          },
          "price":{
            "font-size":"18px"
          },
          "quantityInput":{
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px"
          },
          "compareAt":{
            "font-size":"15px"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "cart":{
        "contents":{
          "button":true
        },
        "events": {
          "updateItemQuantity": function(cart) {
            for (let i = 0; i < ui.components.product.length; i++) {
              var product = ui.components.product[i];
              var node = product.node;
              if ($(node).data('minqty')) {
                var minQty = $(node).data('minqty');
                setTimeout(function() {
                  setProductQuantity(node, product, minQty, ui);
                }, 1);
              }
            }
          }
        }
        "styles":{
          "button":{
            "background-color":"#393a39",
            "font-family":"Lato,sans-serif",
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px",
            ":hover":{
              "background-color":"#333433"
            },
            "border-radius":"0px",
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "footer":{
            "background-color":"#ffffff"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "modalProduct":{
        "contents":{
          "img":false,
          "imgWithCarousel":true,
          "variantTitle":false,
          "buttonWithQuantity":true,
          "button":false,
          "quantity":false
        },
        "styles":{
          "product":{
            "@media(min-width:601px)":{
              "max-width":"100%",
              "margin-left":"0px",
              "margin-bottom":"0px"
            }
          },
          "button":{
            "background-color":"#393a39",
            "font-family":"Lato,sans-serif",
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px",
            "padding-left":"35px",
            "padding-right":"35px",
            ":hover":{
              "background-color":"#333433"
            },
            "border-radius":"0px",
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "quantityInput":{
            "font-size":"13px",
            "padding-top":"14.5px",
            "padding-bottom":"14.5px"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "toggle":{
        "iframe":false,
        "sticky":false,
        "templates":{
          "icon":'<i class="fa fa-shopping-bag fa-lg darkgrey" aria-hidden="true"></i>'
        },
        "contents":{
          "icon":true,
          "title":false
        },
        "events":{
          afterInit:function (component)      {
            document.getElementById('cart-toggle').appendChild(component.node);
          },

        },
        "order":[
          'count',
          'icon'
        ],
        "styles":{
          "toggle":{
            "font-family":"Lato,sans-serif",
            "background-color":"#393a39",
            ":hover":{
              "background-color":"#333433"
            },
            ":focus":{
              "background-color":"#333433"
            },
            "font-weight":"normal"
          },
          "count":{
            "font-size":"13px"
          }
        },
        "googleFonts":[
          "Lato"
        ]
      },
      "productSet":{
        "styles":{
          "products":{
            "@media(min-width:601px)":{
              "margin-left":"-20px"
            }
          }
        }
      }
    }
    }

    );});}})();

    function setProductQuantity(node, product, minQty, ui) {
      if (product.cart.model.lineItemCount < minQty && product.cart.model.lineItemCount > 0) {
        $('.shopify-buy-cart-wrapper').find('iframe').contents().find("div[id='" + product.cart.model.lineItems[0].id + "']").find('.shopify-buy__quantity-decrement').click();
      }
    }
/*]]>*/
</script>