【问题标题】:Using javascript to display selected name使用 javascript 显示选定的名称
【发布时间】:2020-01-18 05:53:02
【问题描述】:

在我的 shopify 主题中,我试图在颜色标签旁边显示颜色名称。例如,如果选择绿色,“颜色:”将变为“颜色:绿色”,如果选择红色,则将变为“颜色:红色”。我目前正在使用一个名为 Basel 的主题。

**巴塞尔主题产品页面 - https://new-basel2.myshopify.com/collections/bag/products/vintage-cinch-backpack

我尝试在我的液体文件中添加几行不同的代码,但没有任何效果。我现在意识到我需要使用 javascript 来做到这一点。这样当一个样本被点击时,它的值就会被获取并放入标签中。

我一点也不精通javascript。如果有人可以帮助编写代码或提供任何帮助,我将非常感激。

swatch.liquid -

{%- include 'check_not_feature_img' -%}
<table class="variations{%- if settings.swatch_design == '2' %} variant_square{%- elsif settings.swatch_design == '3' %} variant_simple{%- endif -%}" cellspacing="0">
   {%- assign option_index = 0 -%}
   {%- if settings.color_name_check != blank -%}{%- assign _gl_color_name = settings.color_name_check | replace: ' ,', ',' | replace: ', ', ',' | split: ',' -%}{%- assign gl_color_name = _gl_color_name | downcase -%}{%-else-%}{%- assign gl_color_name = '\nathan_dt\' -%}{%-endif-%}
   <tbody>
   {%- for option in product.options_with_values -%}
      {%- assign option_index = forloop.index0 -%}
      {%- assign downcased_option = option.name | downcase -%}
      {%- assign downcased_option_check = option.name | downcase | prepend: '"' | append: '"' | strip -%} 
      {%- if downcased_option == 'color' or downcased_option == 'colour' or gl_color_name contains downcased_option_check -%}
            <tr data-option-index="{{ option_index }}" id="gl_select_{{ option_index }}">
               <td class="label"><label for="{{ option_index }}">{{ option.name }}</label></td>
               <td class="value with-swatches">
                  <div class="swatches-select" data-id="{{ option_index }}" data-option-index="{{ option_index }}">
                     {%-assign index = 0 %}
                     {%- for value in option.values -%}
                        <div class="basel-swatch bg_color basel-tooltip swatch-size-{{settings.swatch_size}}{%- if settings.swatch_style == '1' %} colored-swatch{%- else %} image-swatch{%- endif %}{%- if first_available_variant and option.selected_value == value %} active-swatch{%- elsif forloop.first == true and product.selected_variant == blank and first_available_variant == false %} active-swatch{%- elsif option.selected_value == value and product.selected_variant != blank and first_available_variant == false %} active-swatch{%- endif %} bg_color_{{ value  | handleize  }} bg_{{ value  | handleize  }} swatch-enabled" data-value='{{ value | handleize }}' data-image-id="{{ featured_image_id[index] }}">
                           <span class="basel-tooltip-label">{{ value }}</span>{{ value }}
                        </div>
                        {%-assign index = index | plus: 1 %}
                     {%- endfor -%}
                  </div>
               </td>
            </tr>
      {%- else- %}
         <tr data-option-index="{{ option_index }}" id="gl_select_{{ option_index }}">
            <td class="label"><label for="{{ option_index }}">{{ option.name }}</label></td>
            <td class="value with-swatches">
               <div class="swatches-select" data-id="{{ option_index }}" data-option-index="{{ option_index }}">
                 {%- for value in option.values -%}
                     <div class="basel-swatch basel-tooltip text-only swatch-size-{{settings.swatch_size}}{%- if first_available_variant and option.selected_value == value %} active-swatch{%- elsif forloop.first == true and product.selected_variant == blank and first_available_variant == false %} active-swatch{%- elsif option.selected_value == value and product.selected_variant != blank and first_available_variant == false %} active-swatch{%- endif %} bg_{{ value | handleize  }} swatch-enabled" data-value='{{ value | handleize }}'>
                     <span class="basel-tooltip-label">{{ value }}</span>{{ value }}
                     </div>
                 {%- endfor -%}
               </div>
            </td>
         </tr>
      {%- endif -%}
   {%- endfor -%}
   </tbody>
</table>

我需要 javascript 来更改标签后的颜色名称 -

 &lt;td class="label"&gt;&lt;label for="{{ option_index }}"&gt;{{ option.name }}&lt;/label&gt;&lt;/td&gt;

包含var selectCallback = function(variant, selector)的3个文件

product.design_default.liquid - https://gist.github.com/lok343/9e3286aa262b915438c091bf820eebcf

sn-ps/product.json.liquid - https://gist.github.com/lok343/b7251646824b6a9f265b0d7e270f64cd

sn-ps/product_js.liquid - https://gist.github.com/lok343/8690d8a7fb8246f0ca6730899f736050

更新代码

      var selectCallback = function(variant, selector) {
        var selectedOptions = selector.selectedValues(); // This gives an array of all the selected options
var optionData = selector.product.options;  // This gives information about the options set up on the product
var form = selector.variantIdField.form; // This gives us the enclosing form element without needing to do any query-selecting

// Now lets loop through the options and update the elements
for(var i=0; i<selectedOptions.length; i++){
  var optionLabel = form.querySelector('[data-option-index="' + i + '"] label') // This reads, "Find the first <label> element inside the element with the specified data-option-index attribute inside my product form"

  // Let's make sure our code will not break and quickly check to make sure we found the element we were after. If it's blank, continue to the next option. Raising an appropriate error is left as an exercise for the reader.
  if(!optionLabel){
    continue;
  }

  var optionName = typeof optionData[i] === 'object' ? optionData[i].name : optionData[i];  // This is checking to see which of Shopify's 2 different option formats got fed into this function - it could have been either an array of titles or an array of objects that include both the name and an array of all the values. The ( check ? result_if_true : result_if_false ) syntax is called a ternary expression and is shorthand for if(check){ value_if_true } else { value_if_false }
          if (optionName.toLowerCase('Color')) {
  optionLabel.innerText = optionName + ': ' + selectedOptions[i]
          }

}

【问题讨论】:

  • 唯一可行的方法是使用一组预定义的颜色/名称。您的选项数组是否包含颜色名称?如果是这样,当用户选择一种颜色时,使用 JavaScript 在标签旁边设置颜色名称。
  • @TomShaw - 我假设这个用户想要显示的颜色名称将是产品上定义的颜色名称,所以是的 - 肯定会有一个预定义颜色/名称的列表,因为那些将是产品本身:)

标签: javascript jquery html shopify


【解决方案1】:

我查看了您链接的页面,您的主题似乎正在运行一个名为“selectCallback”的函数,只要购物者的选择发生变化。

在您的主题文件中,查找这段代码:

var selectCallback = function(variant, selector)

这标志着您的变体更改功能的开始。此函数正在产品页面上内嵌呈现,因此它可能来自以下文件之一:

  • 基本模板文件 - templates/product.liquid
  • 从基本模板链接的部分 - 如果上面包含 {% section 'some-section-name' %} 在您的 sections 文件夹中查找名为“some-section-name.liquid”的文件
  • 如果不是上述任何一种情况,请尝试渲染产品表单的 sn-p,通常命名为 product-form.liquid 或类似名称
  • 一些主题直接把这个函数放到了基础布局文件中,layout/theme.liquid

找到该函数后,您可以在 javascript 中添加一行以更新所选颜色的标签。名为variant 的变量将是新选择的变体对象(如果选择的选项组合与产品中的变体不匹配,则为null),而名为selector 的变量包含一堆有用的信息。

variant 对象包含 Shopify 必须描述变体的所有信息,包括 variant.options(描述变体的所有选项值的数组)以及 variant.option1variant.option2variant.option3 (参考特定指数的期权价值)。在链接的产品中,颜色是第一个也是唯一的选项维度,因此variant.options[0]variant.option1 是您可以访问当前所选产品的颜色值的两种方式。

如果您需要在任意产品中专门找到颜色选项,并且想忽略任何其他选项名称,我会为您指明selector.product,它可以让您访问完整的产品对象。这意味着selector.product.options 将允许您访问当前产品上的所有选项名称,以便您可以识别哪个维度是彩色的。

示例时间!

这是您可能要添加到此函数的示例。

查看selector 对象,我看到一个名为selectedValues 的函数,它返回一个包含所有当前选定选项的数组。这看起来很有用,因为更复杂的产品可能没有针对每种可能的选项选择组合的变体。 [脚注]

查看文档结构,我看到渲染的代码是这样的:

<tr data-option-index="0" id="gl_select_0">
  <td class="label"><label for="0">Color</label></td>

  <!-- (option-selecting swatches) -->
</tr>

在不更新文档结构的情况下,我们可以将其添加到您的 selectCallback 函数中,这应该可以满足您的大致需求:

var selectedOptions = selector.selectedValues(); // This gives an array of all the selected options
var optionData = selector.product.options;  // This gives information about the options set up on the product
var form = selector.variantIdField.form; // This gives us the enclosing form element without needing to do any query-selecting

// Now lets loop through the options and update the elements
for(var i=0; i<selectedOptions.length; i++){
  var optionLabel = form.querySelector('[data-option-index="' + i + '"] label') // This reads, "Find the first <label> element inside the element with the specified data-option-index attribute inside my product form"

  // Let's make sure our code will not break and quickly check to make sure we found the element we were after. If it's blank, continue to the next option. Raising an appropriate error is left as an exercise for the reader.
  if(!optionLabel){
    continue;
  }

  var optionName = typeof optionData[i] === 'object' ? optionData[i].name : optionData[i];  // This is checking to see which of Shopify's 2 different option formats got fed into this function - it could have been either an array of titles or an array of objects that include both the name and an array of all the values. The ( check ? result_if_true : result_if_false ) syntax is called a ternary expression and is shorthand for if(check){ value_if_true } else { value_if_false }

  optionLabel.innerText = optionName + ': ' + selectedOptions[i]
}

上面的示例代码可以放在selectCallback 函数中的任何位置。我建议将其放置在函数内任何 if() 语句之外的开头或结尾附近,因为无论是否有成功选择的变体,我们都希望它运行。

祝你好运!

[脚注]

要检查 Javascript 对象以了解您可以使用它们做什么,我经常发现以下方法很方便:

  • 在您感兴趣的函数中为您的代码添加断点。(我使用 Chrome 的开发工具手动找到了断点,您可以通过在函数中添加关键字 debugger 来获得捷径)
  • 导航到页面
  • 打开浏览器的开发工具(对于在 Windows 上运行的大多数浏览器,键盘快捷键通常是 F12)
  • 在页面上做一些会触发相关功能的事情(例如:点击不同的颜色样本)
  • 浏览器现在将在遇到断点时暂停。
  • console 选项卡(有时在某些浏览器上称为“调试”)中,您可以键入您感兴趣的变量的名称,您的开发工具应该会自动完成变量名称。您现在可以在控制台中查看不同的属性是什么,运行函数来查看它们的输出,等等。
  • 请记住,如果您将 debugger 添加到源代码中,请务必在完成后通过删除调试代码来清理它:)

【讨论】:

  • 嗨戴夫!谢谢你的回答,我现在才看到这个。我浏览了我的文件并找到了三个带有此代码的文件。我在我原来的问题中链接了上面的文件。您可以为这 3 个文件提供进一步的帮助吗?我真的很感激。
  • 查看页面和您提供的三个文件是否有任何差异,看起来它是具有 `console.log(variant);` 行的那个 - 这仅显示在文件 @ 987654349@。这将是您要更新以添加代码的文件:)
  • 非常感谢!无论如何你可以帮我编辑代码吗? Javascript 不是我的强项。
  • 没有人可以在任何事情上都很强 - 我是我们现代分工的忠实拥护者,因此我不必成为生活各个方面的专家 :) 我已经更新了用一个例子来回答,并添加了一些希望有用的 cmets,如果这是你的长期目标之一,应该可以帮助你开始让你的 javascript 变得更强大:)
  • 非常感谢您的深入回答,非常感谢!好好休息一周!
猜你喜欢
  • 1970-01-01
  • 2013-09-11
  • 1970-01-01
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多