查找具有给定类的下一个元素,无论它在DOM中出现在何处
我很难找到一些我认为应该相对简单的东西。
我需要得到下一个类(div.content),它可能出现在DOM中的某个位置
下面是一些简化的标记,它代表了我所拥有的:
显示给定container
的下一个content
div工作正常,当我尝试从container
的最后一个 content
div到下一个container
中的第一个 content
div时出现问题。
几个要点: –
-
默认情况下, 只有第一个
content
div是可见的,其余的是隐藏的,但我需要一个解决方案,如果例如第四个container
的第二个content
div可见。 -
只能看到一个
content
div。
到目前为止,我设法提出的唯一解决方案似乎非常麻烦,尽管它确实有效。
$('.next').click(function() { $theContent = $(this).parent('.content'); $theContent.hide(); if ($theContent.next('.content').length) { $theContent.next('.content').show(); } else if ($theContent.parent('.container').next('.container') .children('.content').length ) { $theContent.parent('.container').next('.container') .children('.content:first').show(); } else { // reached the end or something went wrong } });
这样做的主要缺点是它依赖于上面的DOM结构,我确信自己会选择一个方法来选择具有给定类的下一个元素,而不管它在DOM中出现的位置。
理想情况下,我想要一个不依赖于任何给定DOM结构的解决方案,如果不可能,任何替代解决方案都会有所帮助!
这是上面例子的小提琴
对不起啰嗦的问题!
事实certificate,这确实是一项非常简单的任务。 通过将选择器传递给jQuery的index()
方法,您可以获得当前元素相对于其集合的索引:
var idx = $theContent.index('div.content') + 1;
然后可以直接定位content
div:
$('div.content').eq(idx).show();
jQuery(function() { var i = 1; jQuery('.content').each(function() { jQuery(this).addClass('content-' + i); i++; jQuery(this).find('a.next').bind('click', function() { toggleContentDivs(jQuery(this).parent()); }); }); }); function toggleContentDivs(oContentDiv) { var nextVisible = false, setVisibility = false; jQuery('.content').each(function() { if (oContentDiv.attr('class') == jQuery(this).attr('class')) { nextVisible = true; jQuery(this).hide(); } else if (nextVisible == true) { jQuery(this).show(); nextVisible = false; setVisibility = true; } else { jQuery(this).hide(); } }); // it must have been the last .content element if (setVisibility == false) { jQuery('.content:first').show(); } }
只有与现有代码的DOM依赖关系,a.next必须是.content的直接子项。
在这里工作jsFiddle示例
结果是一种更简单( 更简洁)的方式来编写它正是你如何减去函数参数:
$theContent.parent().next().length
编辑2:
我广泛地尝试了所有的解决方案,但它们都存在缺陷。 总之,我认为你有最简单的方法。 除非jQuery专家可能会对此有所了解并向我们展示更好的方法。
这是我的最后一个提议:
$('.next').click(function() { $theContent = $(this).parent('.content'); $theContent.hide(10, function() { if (!$theContent.next('.content').length) { $theContent.parent('.container').next() .find('.content:first').show(); } else { $theContent.next('.content').show(); } }); });
理想的解决方案是使用closest()
,但问题是由于容器分离,它的行为不符合我的预期。 在jQuery的例子中,他们使用无序列表。 好吧,这是更容易的,因为你可以区分节点类型(例如li
vs ul
)和简单地做.next('li')
。 在这里你使用所有的div
。 由于某种原因,一旦达到第一个容器的末尾, .closest('.content')
就不起作用了!
这个怎么样:
if ($theContent.next('.content').length) { $theContent.next('.content').show(); } else if ($theContent.parent('.container').next('.container').children('.content').length) { $theContent.parent('.container').next('.container').children('.content:first').show(); } else { $('.content:first').show(); //alert('Reached the end or something went wrong!'); }
的jsfiddle