javascript - 如何添加和删除具有选定选项值的类
问题描述
我想根据 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>
解决方案
为了更好,您可以使用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-->
推荐阅读
- php - 从一个 Apache 虚拟主机上的 Laravel 应用程序到同级虚拟主机上的 Lumen 应用程序的 HTTP 请求:MySQL Access denied for user 'root'@'localhost'
- azure-logic-apps - Azure API 管理添加路径参数
- chatbot - RocketChat:在私人频道上复制消息,因为它们被固定(或加星标)
- php - php函数全局不起作用匿名
- java - JButton 仅在我将鼠标悬停在它上面后才会出现
- php - 检查数据库中的密码和用户名是否正确后显示 toastr
- excel - VBA允许仅复制保护表中的可见单元格
- swift - 带有 SwiftUI 的 Safari 中的标签
- php - 无法从 PHP 中的 mysql 数据库中获取数据
- python-3.x - 除了我指定的之外,颜色栏还显示自动刻度