是否有办法根据某个集合的元素是否具有某个类别来使用boolean parameter来切换集合的元素?我尝试了以下方法,但我认为".person"
与// Would show the entries with the selected country, hide the others
function toggleCountries(country){
$(".person").toggle( $(this).hasClass(country) );
}
...
<select onchange="toggleCountries($(this).val())">
<option value="usa">USA</option>
<option value="canada">Canada</option>
...
</select>
...
<li class="person usa"></li>
<li class="person canada"></li>
<li class="person canada"></li>
<li class="person mexico"></li>
...
DOM:
{{1}}
Sidenote :我知道如何使用多行来切换元素,但我很好奇是否有一种单行方式可以用于将来参考,这可能很有用。
答案 0 :(得分:0)
1。 您可以在country
内使用函数参数toggle()
作为下面的布尔值
function toggleCountries(country){
$(".person").each(function(){
$(this).toggle(!$(this).hasClass(country.toLowerCase()));
});
}
2 val
需要在{strong> 选择框选项中<{1}}
工作代码段: -
value
/*function toggleCountries(country){
$(".person."+country.toLowerCase()).toggle();
}*/
function toggleCountries(country){
$(".person").each(function(){
$(this).toggle(!$(this).hasClass(country.toLowerCase()));
});
}