简体   繁体   English

从字符串中删除空格并比较选项值以隐藏/显示 DIV

[英]Remove white space from string and compare option value to hide/show DIV

I want to hide/show DIV based on the option value of products.我想根据产品的选项值隐藏/显示 DIV。 Basically Shopify added option values automatically, including options that contains more than 1 word.基本上 Shopify 会自动添加选项值,包括包含超过 1 个字的选项。 I don't have much control over that so I thought maybe I can remove the white space from the values and trigger the action.我对此没有太多控制权,所以我想也许我可以从值中删除空格并触发操作。

<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>

Here's the fiddle ==> https://jsfiddle.net/clemckh/qtwuhb7r/14/这是小提琴==> https://jsfiddle.net/clemckh/qtwuhb7r/14/

There was a similar question that was answered but this is different approach so I thought I should create a new thread.有一个类似的问题得到了回答,但这是不同的方法,所以我认为我应该创建一个新线程。 I am a JS beginner so my code is pretty messy.我是 JS 初学者,所以我的代码很乱。 Any help is very much appreciated!很感谢任何形式的帮助!

Try this尝试这个

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM