gpt4 book ai didi

javascript - 使用 Shopify 变体下拉选择

转载 作者:行者123 更新时间:2023-11-30 06:22:08 25 4
gpt4 key购买 nike

在我的产品模板页面中,我有这段代码:

<select name="id" id="ProductSelect-{{ section.id }}" class="product-single__variants">

我正在使用 javascript 片段根据客户的选择隐藏变体。我想为我的所有产品使用一个片段文件,但无法让 javascript 读取以下内容:

var productSelect = "ProductSelect-{{ section.id }}";

我该怎么做?我的替代方案是为每个产品创建一个片段文件,这虽然可能,但它又长又费力。任何想法将不胜感激。

最佳答案

您遇到的问题是 {{ section.id }} 是一个模板变量。在呈现的 HTML 中,该部分被适当的变量替换。一旦您的 javascript 运行,页面上将不会有任何元素在其任何属性中带有双花括号。

有几种方法可以解决这个问题:

想法 1:将部分 ID 存储在某处

为此,您需要有一些地方可以将部分 ID 与已加载到页面上的部分相关联,将该数据与您的代码段在运行时已经知道的内容相关联。

比方说,如果您的代码段知道正在更改的任何产品的产品句柄,您可以在表单中添加如下内容:

<script>
// If our lookup object already exists, do nothing. Otherwise, initialize it as an empty object
window.section_lookup = window.section_lookup || {};

//Now save the section ID using the product's handle
//Using the json filter when we print Liquid variables to Javascript ensures that the resulting value is always Javascript-legal.
section_lookup[{{ product.handle | json}}] = {{ section.id | json }};
</script>

现在,在您的查找代码中,您可以使用:

// Assuming that you have a variable called product_handle already
var productSelect = "ProductSelect-" + section_lookup[product_handle];

这将为您提供您正在寻找的特定 ID。

想法2:利用form对象的力量

您的代码片段是否在您了解包含所需选择元素的任何元素的某些上下文中运行?例如,您是否已经知道表单或产品区域包装器?

如果您的 form 包含您的选择框,那您就太好了。每个表单都知道其中包含的所有表单字段的名称。由于该字段的名称是 id,因此从表单对象进入正确的选择框非常简单:

// Assuming you have a variable named form representing the correct form, access the form field with the name 'id'
var idField = form['id'];

注意:如果您的表单是 jQuery 选择的,您可能不会具有该功能。幸运的是,如果您被 jQuery 包装的对象困住了,您可以像这样轻松地取消包装:

// Assuming somebody gave you a variable named $form that they jQuery-selected....
var form = $form[0];
var idField = form['id'];

如果您没有表单但可以快速访问表单内的任何其他输入,那么您也很幸运 - 每个表单元素(即:输入、选择、文本区域、字段集...)知道它属于什么形式。

// Assuming that there is a variable named target which is a form element contained in the same form as the ID field that we want:
var form = target.form;
var idField = form['id'];

想法 3:使用一些其他包装元素来约束您的查找

如果您对某些包含您想要的选择框但不包含您不需要的选择框的包装元素一无所知,您可以将您的查询选择器限制为仅查看包装器内部。这样,您只会找到所需的元素。

如果您使用普通的“ Vanilla ”Javascript:

//Assuming we have a variable named product_wrapper
var idField = product_wrapper.querySelector('[name="id"]');

或者如果您更喜欢 jQuery:

//Still assuming that we have a variable named product_wrapper
var idField = jQuery('[name="id"]', product_wrapper);

希望您至少可以通过其中一种方法获得成功。祝你好运!

关于javascript - 使用 Shopify 变体下拉选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52541821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com