javascript - 如果元素有类,则切换元素

标签 javascript jquery

有没有一种方法可以根据元素是否具有某个类来切换集合的元素 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/

相关文章:

javascript - 有没有办法在没有jquery的情况下获得表兄弟元素类?

javascript - 将替换值从对象存储到另一个数组

jquery - 如何在使用 jquery 编辑框阴影期间使 rba 功能起作用?

jquery - 更改多个元素的类

javascript - jQuery 完整日历 : set a different color to each event from front-end

javascript - 加载 View 后express.js传递变量

javascript - 在 Highcharts 中添加额外的工具提示

javascript - jPlayer 视频无法在 iOs - iPad 和 iPhone 中播放

jquery - 使用 jQuery 制作可切换的导航栏

javascript - 如何在鼠标悬停按钮时显示或隐藏面板