首页 > 解决方案 > 从字符串中删除空格并比较选项值以隐藏/显示 DIV

问题描述

我想根据产品的选项值隐藏/显示 DIV。基本上 Shopify 会自动添加选项值,包括包含超过 1 个单词的选项。我对此没有太多控制权,所以我想也许我可以从值中删除空格并触发操作。

<Select id="single-option-selector-product-template-0">
   <option value="Heather Ash">Heather Ash</option>
</Select>

<div id="HeatherAsh" class="colours" style="display:none">Heather Ash </div>

这是小提琴==> https://jsfiddle.net/clemckh/qtwuhb7r/14/

有一个类似的问题得到了回答,但这是不同的方法,所以我认为我应该创建一个新线程。我是 JS 初学者,所以我的代码很乱。很感谢任何形式的帮助!

标签: javascriptjquery

解决方案


尝试这个

jQuery(function() {
      jQuery('#single-option-selector-product-template-0').change(function() {
        $('.colours').hide();
        var optionValue = jQuery(this).val();
        optionValue = optionValue.replace(/\s+/g, '');
        $('#' + optionValue).show();
      });
    });
<Select id="single-option-selector-product-template-0">
   <option value="White">White</option>
   <option value="Navy">Navy</option>
   <option value="Heather Ash">Heather Ash</option>
   <option value="Heather Grey">Heather Grey</option>
</Select>
<div id="White" class="colours" style="display:none"> White </div>
<div id="Navy" class="colours" style="display:none"> Navy </div>
<div id="HeatherAsh" class="colours" style="display:none">Heather Ash </div>
<div id="HeatherGrey" class="colours" style="display:none"> Heather Grey </div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


推荐阅读