首页 > 解决方案 > 如何添加和删除具有选定选项值的类

问题描述

我想根据 jQuery/JavaScript 选择的值只显示一个 div id a OR b ,比如如果选择的值是 s-license,那么 div id a应该显示并且b应该被隐藏,如果选择的值是 e-license 然后b应该显示,应该隐藏,希望你明白我的意思,对不起,我的英语不好。

<select class="form-control" name="attribute_pa_license" id="uniqueid">
<option value="s-license" class="attached enabled">S License</option>
<option value="e-license" class="attached enabled">E License</option>

<div id="a">Some Text</div> <div id="b">Some Text</div>

标签: javascriptjqueryhtml

解决方案


为了更好,您可以使用data-attribute来实现它。

1.将data-value属性添加到您的div并添加选择框选项的相应值。

2.最初隐藏div($('div').hide();)。(这将隐藏页面上的所有div,因此最好使用一个通用的div类并使用该类隐藏特定的div)

3.在选择框更改时,将所选值与data-value相应 div 的值进行比较并显示出来。

工作片段: -

$('div').hide(); // initially hide divs
$('div[data-value='+ $('#uniqueid').val()+']').show(); // initially show the selected option corresponding div
$('#uniqueid').change(function(){ // on select-box change
  $('div').hide(); // first hide div
  $('div[data-value='+ $(this).val()+']').show(); // based on option value check which div data-value matched, just show that div only
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="attribute_pa_license" id="uniqueid">
<option value="s-license" class="attached enabled">S License</option>
<option value="e-license" class="attached enabled">E License</option>
</select>
<div data-value="s-license" id="a">Some Text</div><!-- add data attribute to div and give corresponding option values in it-->
<div data-value="e-license" id="b">Some Text2</div><!-- add data attribute to div and give corresponding option values in it-->

注意:- 如果您也无法稍微更改 HTML,请执行以下操作:-

$('div').hide();
$('div').eq($('#uniqueid option:selected').index()).show();
$('#uniqueid').change(function(){
  $('div').hide();
  $('div').eq($('#uniqueid option:selected').index()).show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="attribute_pa_license" id="uniqueid">
<option value="s-license" class="attached enabled">S License</option>
<option value="e-license" class="attached enabled">E License</option>
</select>
<div data-value="s-license" id="a">Some Text</div><!-- add data attribute to div and give corresponding option values in it-->
<div data-value="e-license" id="b">Some Text2</div><!-- add data attribute to div and give corresponding option values in it-->


推荐阅读