【问题标题】:Shopify Hide unavailable option variantsShopify 隐藏不可用的选项变体
【发布时间】:2019-11-19 00:59:48
【问题描述】:

使用 Shopify 中的 Debut 主题,我有一个产品的变体不兼容。目前它们显示为不可用,但我想完全隐藏它们,以便只有有效的选项才能相互显示。例如,如果我有红色、蓝色、绿色的鞋子并且尺寸为 9、10、11。但只能买 10 码的红鞋。我不想看到 9 码或 11 码的选择。

网上有人指点theme.js和下面的代码,但是不知道改什么。

谢谢

$(this.singleOptionSelector, this.$container).on(
  'change',
  this._onSelectChange.bind(this)
);

}

【问题讨论】:

  • 我认为这是一个液体代码而不是一个 js 问题,您可能想在产品模板中更改液体代码。但是这样的改变会非常复杂,因为如果蓝色的尺寸为 9、11,我相信你仍然会看到红色的选项 9、11

标签: ruby shopify liquid


【解决方案1】:

我花了一天的大部分时间在这上面,并想出了以下内容,这似乎在我正在开发的网站上运行良好。

我想出的答案涉及编辑 assets/theme.js 文件。目前,下面的代码通过检查可用的变体组合来禁用不相关的选择选项,但您可以轻松地修改下面的代码以隐藏它们,然后用 CSS 显示它们。

assets/theme.js

  1. 下面的 _hideUnavailableOptions 方法需要添加到 Variants.prototype 对象中。
  2. 然后您需要从两个不同的地方调用该方法,见下文。

    _hideUnavailableOptions: function() {
      const option1 = document.getElementById("SingleOptionSelector-0");
      const option2 = document.getElementById("SingleOptionSelector-1");
    if (option2) {
      const secondOptions = option2.options;      
      const variants = this.product.variants;
      let possibles = [];
      variants.forEach((variant) => {
        if (variant.options.includes(option1.value)) {
        possibles.push(variant.options)
      }
     })
     for (let option of secondOptions) {
        const value = option.value;
        let flag = false;
        possibles.forEach((possible) => {
         if (possible.includes(value)) {
         flag = true;
        }
      })
      if (flag === false) {
        option.removeAttribute('selected');
        option.setAttribute('disabled', 'disabled');
      } else {
       option.removeAttribute('disabled');
      }
     } option2.querySelector(':not([disabled="disabled"])').setAttribute('selected', 'selected');
     }
    },
    

调用方法如下:

function Variants(options) {

  //stuff before this, then...

  this.enableHistoryState = options.enableHistoryState;
  this._hideUnavailableOptions();  //N.B. this MUST be before the next line
  this.currentVariant = this._getVariantFromOptions(); 
}

...再次调用 Variants.prototype._onSelectChange() 中的方法 - 确保它是其中的第一行...

_onSelectChange: function() {
    let hideUnavailable = this._hideUnavailableOptions(); //N.B. this MUST be before the next line
    var variant = this._getVariantFromOptions();

    //lots more stuff follows...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 2015-04-27
    • 2013-01-06
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多