【问题标题】:Working with Shopify Variants dropdown select使用 Shopify 变体下拉选择
【发布时间】:2023-03-27 22:30:01
【问题描述】:

在我的产品模板页面我有这个代码:

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

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

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

我该怎么做?我的替代方案是,我为每个产品都有一个 sn-p 文件,虽然可能,但它变得漫长而艰巨。 任何想法将不胜感激。

【问题讨论】:

  • 你可以使用document.querySelector("select[id^=ProductSelect]").value来抢值。除非你有多个&lt;select&gt;s?
  • 不幸的是页面上有两个选择。

标签: javascript shopify liquid


【解决方案1】:

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

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

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

为此,您需要有一些地方可以将部分 ID 与页面上已加载的部分相关联,将那段数据与您的 sn-p 在运行时已经知道的内容联系起来。

如果您的 sn-p 知道正在更改的任何产品的产品句柄,您可以在表单中添加类似这样的内容:

<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 对象的强大功能

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

如果您有包含您的选择框的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:使用其他一些包装元素来约束您的查找

如果您对包含您想要的选择框并且不包含您不想要的选择框的包装元素有所了解,您可以将查询选择器限制为仅查看包装器内部。这样,您只会找到您需要的元素。

如果您使用的是普通的“香草”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);

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

【讨论】:

    猜你喜欢
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多