如果元素具有类,则切换元素

3

是否有一种方法可以使用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
$(".person.canada").toggle() - gaetanoM
当更改选择时,您的列表应该发生什么变化? - j08691
显示选定国家的<li>,其他被隐藏... 真的很抱歉,伙计们,我以为我的问题很简单,没有意识到会有这么多误解的空间 :/ - user2608458
谢谢,我已经编辑过了。 - user2608458
1
谢谢 @Mike,我正在使用这个情况作为一个例子来了解是否可能在“toggle”函数内部访问$(this),因为知道如何使用this可能在其他情况下证明有用。 - user2608458
显示剩余4条评论
1个回答

0

1. 你可以在 toggle() 函数中像下面这样使用函数参数 country 作为布尔值

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>


抱歉我的问题有些混乱,非常感谢你的帮助朋友。然而,我需要一个布尔值作为“toggle()”方法中的参数来显示或隐藏元素。 - user2608458
包在一个foreach循环里?我也在考虑这样做,但不确定是否还有其他方法 :) 那好吧,我猜就是这样做,谢谢朋友! - user2608458
@user2608458 很高兴能帮助你 :):) - Alive to die - Anant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接