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

标签 javascript jquery html

我只想根据 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/

相关文章:

javascript - 我在网站上做的过渡效果有问题?

javascript - 从 Java 脚本中的数组列表中排除 ID 列表

javascript - 如何在获取元素值之前检查数据是否已加载到元素中

javascript - 在提交表单之前显示一个 css 弹出窗口

Javascript 翻转/镜像图像

javascript - 实现没有Position属性的绝对定位,使用Margin/Padding

java - 嵌套的要点列表文本到 HTML

javascript - jQuery:搜索相同的多个值

jquery - SVG stroke-dashoffset 动画在点击时(再次)开始

javascript - 是否有一个 "onload"-类似的事件监听器用于在 Javascript 中添加到 DOM 的新元素?