某个元素后面的*整个*文档中的下一个元素 [英] Next element in *entire* document after certain element
问题描述
这是一个问题的一个变化,这么多次。给定任何元素,我想在整个文档中找到任何其他元素。它可以是一个兄弟姐妹,但它也可能是以后发生的任何其他元素。例如,给定以下标记:
This is a variation on a question asked so many times. Given any element, I want to be able to find any other element after it in the entire document. It can be a sibling but it could also be any other element that occurs afterward. For example, given the following markup,
<div>
<p>Hello</p>
<div>
<p>Foo</p>
<p class="bar">Bar</p>
<p>rawr!</p>
</div>
<p>bop</p>
<input/>
<div>
<p>Another</p>
<div>
<span>something</span>
<p>deep!</p>
</div>
</div>
</div>
<p>last</p>
为了描述这个原因,让我们说我正在寻找的函数称为$ code> $。fn.nextInDocument 。如果我打电话:
For the sake of this description, lets say the function I am looking for is called $.fn.nextInDocument
. If I called:
$('.bar').nextInDocument('p'); // <p>rawr</p>
$('.bar').nextInDocument('p').nextInDocument('p'); // <p>bop</p>
继续,将获得< p>另一个< / p>
,然后< p>深!< / p>
最后< p> last< / p>
。
Continuing on, it would get <p>Another</p>
, then <p>deep!</p>
and finally <p>last</p>
.
是否存在这样的事情?我不在乎它是一个选择器还是功能。我只需要这个功能。
Does something like this exist? I don't care if it is a selector or a function. I just need the functionality.
编辑更新了DOM结构,使其成为一个更具挑战性的问题,更清楚我正在寻找什么。
EDIT Updated the DOM structure to make it a more challenging question yet more clear for what I am looking for.
推荐答案
这个怎么样?这是一个通用的解决方案,它使用DOM方法依次遍历节点,并针对jQuery选择器进行测试。
How about this? It's a generic solution that uses DOM methods to traverse nodes in turn and tests each against the jQuery selector.
jsFiddle: http://jsfiddle.net/PsEdZ/3/
jsFiddle: http://jsfiddle.net/PsEdZ/3/
(function($) {
function nextNode(node, omitChildren) {
var sibling, parentNode;
if (!omitChildren && node.hasChildNodes()) {
return node.firstChild;
} else {
sibling = node.nextSibling;
if (sibling) {
return sibling;
} else {
parentNode = node.parentNode;
return parentNode ? nextNode(parentNode, true) : null;
}
}
}
$.fn.nextInDocument = function(selector) {
var node = this[0], $node;
while ( (node = nextNode(node)) ) {
$node = $(node);
if ($node.is(selector)) {
return $node;
}
}
return null;
}
})(jQuery);
这篇关于某个元素后面的*整个*文档中的下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!