Jquery切换具有特定类的最近项

时间:2018-05-17 01:14:36

标签: javascript jquery html

我正在尝试用特定的类来切换一些项目。什么是代码问题?

//show hide items with class Network

$(document).ready(function() {

  $('.testCategory').click(function() {
    $(this).closest('.Network').toggle();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="testCategory">Network</a>
<a href="#" class="Network none">RTT</a>
<a href="#" class="Network none">Capacity</a>
<a href="#" class="Network none">Jitter</a>

2 个答案:

答案 0 :(得分:3)

.closest()遍历DOM。您可能需要nextAll()代替:

$('.testCategory').click(function(){
   $(this).nextAll('.Network').toggle();
});

&#13;
&#13;
$(document).ready(function() {
  $('.testCategory').click(function() {
    $(this).nextAll('.Network').toggle();
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="testCategory">Network</a>
<a href="#" class="Network none">RTT</a>
<a href="#" class="Network none">Capacity</a>
<a href="#" class="Network none">Jitter</a>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您希望nextAll()代替

  

获取匹配组中每个元素的所有兄弟姐妹   元素,可选择由选择器过滤。

&#13;
&#13;
$('.testCategory').click(function() {
  $(this).nextAll('.Network').toggle();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="testCategory">Network</a>
<a href="#" class="Network none">RTT</a>
<a href="#" class="Network none">Capacity</a>
<a href="#" class="Network none">Jitter</a>
&#13;
&#13;
&#13;