简体   繁体   English

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

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

I am building a custom "subscription builder" where customers select options, proceed to the next step and at the end click checkout; 我正在构建一个自定义的“订阅生成器”,客户可以在其中选择选项,继续进行下一步,最后单击结帐; their options reflected in the variant selected. 它们的选项反映在所选的变体中。

The way Im going about this is by hiding shopify's selectors and setting them manually using $().val(); 我要解决的方法是隐藏shopify的选择器,并使用$()。val()手动设置它们。 This accurately changes the selectors (checking in inspector), but Shopify does not recognize these changes for some reason and so the product added to the cart is the default. 这样可以准确地更改选择器(在检查器中签入),但是Shopify由于某些原因无法识别这些更改,因此添加到购物车的产品是默认设置。 I am obviously missing something - is this even possible? 我显然缺少了一些东西-这可能吗?

[Code Redacted for uselessness] [因无用而删除的代码]

Thank you! 谢谢!

Basically, 基本上,

Shopify's option_selection.js controls this and has a "Product" and "OptionSelector" object. Shopify的option_selection.js对此进行控制,并具有“产品”和“ OptionSelector”对象。

OptionSelector has a function selectVariant(id, selector) that will properly set it given you have the full variant identifier. OptionSelector具有功能selectVariant(id,选择器),如果您具有完整的变体标识符,它将正确设置它。

In your product_form.liquid you will see a place that does new OptionSelector(args). 在product_form.liquid中,您将看到一个执行新OptionSelector(args)的地方。 You simply save what it returns, ie 您只需保存返回的内容,即

selector = new OptionSelector(...); 

then you can do 那你就可以

selector.selectVariant("123456789", selector); 

This will properly set the variant for the checkout button. 这将正确设置签出按钮的变体。 You can then either hide the 'shopify' selectors with css / js or keep them or modify the option_selection.js code yourself by downloading from here . 然后,您可以使用css / js隐藏“ shopify”选择器,或者保留它们,或者通过从此处下载自己修改option_selection.js代码。

Furthermore, I've discovered more useful things one can do: 此外,我发现了一个人可以做的更有用的事情:

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

EDIT: Dave has kindly pointed out that 编辑:戴夫好心指出

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

Would have done what I wanted, but points out (and I agree) that using OptionSelector is more of a robust method. 本来可以完成我想要的,但是指出(我同意),使用OptionSelector更可靠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM