【问题标题】:Select prepended option by default默认选择前置选项
【发布时间】:2016-10-13 21:52:26
【问题描述】:

好的,我要拔头发了。

我希望有人可以帮助我。

我正在尝试在下拉菜单中添加“选择选项”值,然后在页面加载时将其设为默认选择。

简要介绍一下背景:我一直在尝试结合 Shopify 的“链接选项”和“选择选项”功能。遗憾的是,当您尝试同时实现这两者时,链接选项功能会覆盖选择选项。 (选择一个选项会在下拉菜单中放置一个默认的“选择 ____”)。

所以我参与了“选择一个选项”并尝试将其放在“链接选项”中。

这是我放在那里的代码:

selector.prepend('<option value="">Select ' + {{ product.options[forloop.index0] | json }} + '</option>').val('');

这是完整的代码:

<script>
// (c) Copyright 2016 Caroline Schnapp. All Rights Reserved. Contact:     mllegeorgesand@gmail.com
// See https://docs.shopify.com/themes/customization/navigation/link-product-    options-in-menus

var Shopify = Shopify || {};

Shopify.optionsMap = {};

Shopify.updateOptionsInSelector = function(selectorIndex) {

  switch (selectorIndex) {
    case 0:
      var key = 'root';
      var selector = jQuery('.single-option-selector:eq(0)');
      break;
case 1:
  var key = jQuery('.single-option-selector:eq(0)').val();
  var selector = jQuery('.single-option-selector:eq(1)');
  break;
case 2:
  var key = jQuery('.single-option-selector:eq(0)').val();  
  key += ' / ' + jQuery('.single-option-selector:eq(1)').val();
  var selector = jQuery('.single-option-selector:eq(2)');
  }

  var initialValue = selector.val();

  selector.empty();    
  var availableOptions = Shopify.optionsMap[key];
  selector.prepend('<option value="">Select ' + {{ product.options[forloop.index0] | json }} + '</option>');
  selector[0].selectedIndex = 0;
  for (var i=0; i<availableOptions.length; i++) {
var option = availableOptions[i];
var newOption = jQuery('<option></option>').val(option).html(option).val('');
selector.append(newOption);
  }
  jQuery('.swatch[data-option-index="' + selectorIndex + '"] .swatch-element').each(function() {
    if (jQuery.inArray($(this).attr('data-value'), availableOptions) !== -1) {
      $(this).removeClass('soldout').show().find(':radio').removeAttr('disabled','disabled').removeAttr('checked');
}
else {
      $(this).addClass('soldout').hide().find(':radio').removeAttr('checked').attr('disabled','disabled');
}
  });
  if (jQuery.inArray(initialValue, availableOptions) !== -1) {
selector.val(initialValue);
  }
  selector.trigger('change');  

};

Shopify.linkOptionSelectors = function(product) {

  // Building our mapping object.
  for (var i=0; i<product.variants.length; i++) {
    var variant = product.variants[i];
    if (variant.available) {
  // Gathering values for the 1st drop-down.
  Shopify.optionsMap['root'] = Shopify.optionsMap['root'] || [];
  Shopify.optionsMap['root'].push(variant.option1);
  Shopify.optionsMap['root'] = Shopify.uniq(Shopify.optionsMap['root']);
  // Gathering values for the 2nd drop-down.
  if (product.options.length > 1) {
    var key = variant.option1;
    Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];
    Shopify.optionsMap[key].push(variant.option2);
    Shopify.optionsMap[key] = Shopify.uniq(Shopify.optionsMap[key]);
  }
  // Gathering values for the 3rd drop-down.
  if (product.options.length === 3) {
    var key = variant.option1 + ' / ' + variant.option2;
    Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];
    Shopify.optionsMap[key].push(variant.option3);
    Shopify.optionsMap[key] = Shopify.uniq(Shopify.optionsMap[key]);
  }
}
  }
// Update options right away.
  Shopify.updateOptionsInSelector(0);
  if (product.options.length > 1) Shopify.updateOptionsInSelector(1);
  if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
  // When there is an update in the first dropdown.
  jQuery(".single-option-selector:eq(0)").change(function() {
    Shopify.updateOptionsInSelector(1);
    if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
    return true;
  });
  // When there is an update in the second dropdown.
  jQuery(".single-option-selector:eq(1)").change(function() {
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
return true;
  });  
};

{% if product.available and product.options.size > 1 %}
  var $addToCartForm = $('form[action="/cart/add"]');
  if (window.MutationObserver && $addToCartForm.length) {
    if (typeof observer === 'object' && typeof observer.disconnect === 'function') {
      observer.disconnect();
    }
    var config = { childList: true, subtree: true };
var observer = new MutationObserver(function() {      
  Shopify.linkOptionSelectors({{ product | json }});
  observer.disconnect();
});  
observer.observe($addToCartForm[0], config);
  }
{% endif %}

【问题讨论】:

    标签: javascript jquery html shopify liquid


    【解决方案1】:

    看起来要花太多时间去摸索。片段 1 演示了如何在选择前添加选项。片段 2 演示了如何使用 insertAdjacentHTML()。属性:selected,其值可以是:"selected"true/false,目的是指定默认选项。代码中有详细注释。

    片段 1

    // Reference the select
    var sel = document.getElementById('sel');
    // Create an option
    var opt = document.createElement('option');
    // Add a value
    opt.value = '0';
    // Add content
    opt.textContent = '0';
    // Make it default
    opt.setAttribute('selected', true);
    // Reference the first child of the select
    var first = sel.firstChild;
    // Insert box before the first 
    sel.insertBefore(opt, first);
    <select id='sel' name='sel'>
      <option value='1'>1</option>
      <option value='2'>2</option>
      <option value='3'>3</option>
      <option value='4'>4</option>
    </select>

    片段 2

    var sel = document.getElementById('sel');
    
    sel.insertAdjacentHTML('afterbegin', '<option value="" selected=true>Select</option>');
    
    // Reference the first child of select
    var first = sel.firstChild;
    // This commented out because I don't have the data to use it.
    // first.textContent = "Select "+{{product.options[forloop.index0] || json}}+";
    <script src='https://cdn.jsdelivr.net/handlebarsjs/4.0.5/handlebars.min.js'></script>
    <select id='sel' name='sel'>
      <option value='1'>1</option>
      <option value='2'>2</option>
      <option value='3'>3</option>
      <option value='4'>4</option>
    </select>

    insertAdjacentHTML()的第一个参数是插入的位置:

     <section id='s1'>Content xxxxxxxxxxxxxxxxxxxxx</section>
    ▲-----------------▲----------------------------▲---------▲
    

    beforebegin___afterbegin________________beforeend_afterend

    第二个参数是要解析成 HTML 的字符串。基本上inserAdjacentHTML() 是类固醇上的innerHTML。阅读here

    【讨论】:

      猜你喜欢
      • 2015-09-19
      • 2017-12-18
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 2021-06-02
      相关资源
      最近更新 更多