[英]How can I make an element visible or not with the select tag?
我将尽力解释这个问题。 我在html中有此选择:
<select id="seasons" multiple="multiple">
<option value="s01">Stagione 1</option>
<option value="s02">Stagione 2</option>
<option value="s03">Stagione 3</option>
<option value="s04">Stagione 4</option>
<option value="s08">Stagione 8</option>
</select>
如您所见,这是一个多项选择。 现在,我必须检查是否已选中并且仅显示选中的项目,而未选中的项目必须隐藏。
我必须显示或隐藏的元素具有一个等于这些选项的值的类(该元素是表格):
<table class="s01">
...
</table>
尝试这个
$(function(){
$('table').hide(); //<--this hides all the table
$('#seasons').change(function(){
$.each($(this).val(),function(i,v){
$('.'+v).show();
}
});
});
因为, $('table').hide();
隐藏文档中存在的所有表...您可以将相同的类添加到要隐藏的特定表中,并使用类选择器$('.tableClass').hide()
。
multiple
选择元素的.val()
方法返回所选值的数组,您可以.join()
这些值并使用生成的选择器过滤表。
$('#seasons').on('change', function() {
var selector = this.selectedIndex > -1 ? '.' + $(this).val().join(',.') : null;
$('table').hide().filter(selector).show();
});
您可以将s
类与sxx
类一起添加到所有目标元素,然后
<table class="s s02">
<tr>
<td>01</td>
</tr>
</table>
然后
var $els = $('.s').hide();
$('#seasons').change(function () {
var selected = $(this).val(),
$sel;
if (selected && selected.length > 0) {
$sel = $els.filter('.' + selected.join(', .')).show();
$els.not($sel).hide();
} else {
$els.hide();
}
})
演示: 小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.