Jef*_*eff 5 html javascript jquery dom
这是对这么多问题的变化.给定任何元素,我希望能够在整个文档中找到其后的任何元素.它可以是兄弟姐妹,但也可能是之后发生的任何其他元素.例如,给定以下标记,
<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>
Run Code Online (Sandbox Code Playgroud)
为了这个描述,让我们说我正在寻找的功能被调用$.fn.nextInDocument.如果我打电话:
$('.bar').nextInDocument('p'); // <p>rawr</p>
$('.bar').nextInDocument('p').nextInDocument('p'); // <p>bop</p>
Run Code Online (Sandbox Code Playgroud)
继续,它会<p>Another</p>,然后<p>deep!</p>,最后<p>last</p>.
这样的事情存在吗?我不在乎它是选择器还是功能.我只需要这个功能.
编辑更新了DOM结构,使其成为一个更具挑战性的问题,但更清楚我正在寻找什么.
这个怎么样?这是一个通用的解决方案,使用 DOM 方法依次遍历节点并针对 jQuery 选择器测试每个节点。
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
245 次 |
| 最近记录: |