在我的产品模板页面中,我有这样的代码:
<select name="id" id="ProductSelect-{{ section.id }}" class="product-single__variants">我正在使用一个javascript代码片段来隐藏基于客户选择的变体。我想对我的所有产品使用一个代码片段文件,但无法让javascript读取以下内容:
var productSelect = "ProductSelect-{{ section.id }}";我该怎么做呢?我的另一种选择是,我为每个产品都有一个代码片段文件,虽然这是可能的,但这会使它变得冗长而繁琐。任何想法都将不胜感激。
发布于 2018-10-02 00:25:50
您遇到的问题是{{ 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对象的强大功能
您的代码片段是否在某个上下文中运行,其中您知道包含所需select元素的任何元素的某些信息?例如,您是否已经知道表单或产品区域包装器?
如果您有包含选择框的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'];如果您没有表单,但您可以快速访问表单中的任何其他输入,那么您也很幸运-每个表单元素(即: input、select、textareas、fieldsets...)也知道它属于什么形式。
// 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);希望你能用这些方法中的至少一种来获得成功。祝好运!
https://stackoverflow.com/questions/52541821
复制相似问题