首页 > 解决方案 > Jquery切换具有特定类的最近项目

问题描述

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

//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>

标签: javascriptjqueryhtml

解决方案


.closest()遍历 DOM。您可能想要nextAll()

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

$(document).ready(function() {
  $('.testCategory').click(function() {
    $(this).nextAll('.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>


推荐阅读