如何找到具有相同类的父元素的下一个元素



尝试使父项的特定兄弟项淡入或淡出。

<header class="myheader">
   <h1 class="title">Title 1</h1>
</header>
<ul class="my-list">
   <li>list item 1</li>
</ul>
<header class="myheader">
   <h1 class="title">Title 2</h1>
</header>
<p>description</p>
<ul class="my-list">
   <li>list item 1</li>
   <li>list item 2</li>
   <li>list item 3</li>
</ul>
<header class="myheader">
   <h1 class="title">Title 3</h1>
</header>
<ul class="my-list">
   <li>list item 1</li>
   <li>list item 2</li>
   <li>list item 3</li>
</ul>   
因此,使用上面的标记,我希望能够点击任何标题h1标签,并使下一个ul块可见(淡出)。

使用这个jQuery,我可以隐藏所有的ul块(在jQuery中完成,所以如果js关闭所有内容仍然可见),然后等待标题h1标签上的点击事件,带有'myheading'类,并使最接近的下一个兄弟ul块逐渐消失。

jQuery(document).ready(function($) {
  $('.title').each(function() {
      $('ul.my-list').hide();
      $(this).click(function() {
         $(this).parent().next('ul.my-list').fadeToggle();
         return false;
      });
   });
});

但是,对于第二个标题,这将失败,因为它在ul块之前有一个段落标记。

我如何针对每个标题h1正确的ul标签?由于jQuery .next()只查找最近邻的元素,它不会使用指定的搜索参数(如'ul'或类)搜索最近的下一个元素。

我尝试了各种版本的.find(), .next(), . nextall()等没有成功。我不想在标签中添加id,因为这会破坏使用this()的意义。

任何想法?

使用nextAll('ul.my-list:first')

next仅限第一个相邻项。

nextAll返回所有后续项,然后可以过滤返回第一个项。

你也可以做nextAll('ul.my-list').first()如果你喜欢(应该是稍微快一点)

JsFiddle: http://jsfiddle.net/TrueBlueAussie/8ddnV/

相关内容

最新更新