有没有一种方法可以根据元素是否具有某个类来切换集合的元素 boolean parameter ?我尝试了以下方法,但我认为 $(this)
与 ".person"
// Would show the entries with the selected country, hide the others
function toggleCountries(country){
$(".person").toggle( $(this).hasClass(country) );
}
DOM:
...
<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>
...
旁注:我知道如何使用多行切换元素,但我很好奇是否有一种单行方法可以供将来引用,可能会有用。
最佳答案
1.您可以使用函数参数 country
里面toggle()
作为 bool 值,如下所示
function toggleCountries(country){
$(".person").each(function(){
$(this).toggle(!$(this).hasClass(country.toLowerCase()));
});
}
2 val
需要value
在选择框选项
工作片段:-
/*function toggleCountries(country){
$(".person."+country.toLowerCase()).toggle();
}*/
function toggleCountries(country){
$(".person").each(function(){
$(this).toggle(!$(this).hasClass(country.toLowerCase()));
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select onchange="toggleCountries($(this).val())">
<option value="usa">USA</option>
<option value="canada">Canada</option>
</select>
<li class="person usa">q</li>
<li class="person canada">m</li>
<li class="person canada">n</li>
<li class="person mexico">b</li>
关于javascript - 如果元素有类,则切换元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49578387/