gpt4 book ai didi

javascript - 如何使用选定的选项值添加和删除类

转载 作者:行者123 更新时间:2023-11-28 13:01:31 25 4
gpt4 key购买 nike

我只想根据 jQuery/JavaScript 所选值仅显示一个 div id ab,就像如果所选值是 s-license 那么 div id a 应显示,b 应隐藏,如果所选值是电子许可证,则应显示 ba应该隐藏,我希望你明白我的意思,抱歉我的英语不好。

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

最佳答案

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

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

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

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

工作片段:-

$('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-->

关于javascript - 如何使用选定的选项值添加和删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50000706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com