设置 Shopify 选项选择器的值/通过 javascript 更改所选变体

SET the value of a Shopify Option Selector / change selected variant via javascript

我正在构建自定义 "subscription builder" 客户 select 选项,继续下一步并在最后单击结帐;他们的选择反映在变体 selected 中。

我解决这个问题的方法是隐藏 shopify 的 selector 并使用 $().val(); 手动设置它们;这准确地更改了 selectors(在检查器中检查),但 Shopify 出于某种原因无法识别这些更改,因此添加到购物车的产品是默认的。我显然遗漏了一些东西——这有可能吗?

[已编辑无用的代码]

谢谢!

基本上,

Shopify 的 option_selection.js 控制它并有一个 "Product" 和 "OptionSelector" 对象。

OptionSelector 有一个函数 selectVariant(id, selector) ,如果你有完整的变体标识符,它会正确地设置它。

在您的 product_form.liquid 中,您会看到一个执行 new OptionSelector(args) 的地方。您只需保存它 returns,即

selector = new OptionSelector(...); 

那么你可以

selector.selectVariant("123456789", selector); 

这将正确设置结帐按钮的变体。然后,您可以使用 css / js 隐藏 'shopify' 选择器,或者保留它们或通过从 here 下载自己修改 option_selection.js 代码。

此外,我还发现了更多有用的事情:

selector.selectors[index].element.value {get; set;} //much cleaner method of accessing selector elements 
selector.product.getVariant(selector.selectedValues()).id // gets the variant id for you so you do not need to hardcore them in

编辑:Dave 友善地指出

$(element).val(newValue).trigger('change'); 

本来可以做我想做的,但指出(我同意)使用 OptionSelector 是一种更可靠的方法。