找到DOM中稍后出现的下一个元素
在javascript中可能更好,但这肯定包括jQuery或任何这样的库。
我想在下面的例子中找到第一个.next
。
类似的问题有很多答案,表明nextAll
或siblings
……两者在这里都没用:
$(function(){ $('.result').text( $('.origin').nextAll('.next').text() || $('.origin').siblings('.next').text() || 'both failed' ) })
1
2
3
此外,最兼容(浏览器和库明智)和最佳性能(速度和更少的代码行)的方式是这样做的吗?
基于@mrtsherman的精彩回答 ,我编写了这个更完整的解决方案并对其进行了测试,以便在Chrome和Safari上运行:
$(function() { $('.result').text( $('.origin').below('.next').text() ); }); (function($) { $.fn.below = function(sel) { var $result = $(sel).first(); if ($result.length <= 0) { return $result; } $result = []; var thisIndex = $('*').index($(this)); var selIndex = Number.MAX_VALUE; // Number.MAX_SAFE_INTEGER is not yet fully supported $(sel).each(function(i, val) { var valIndex = $('*').index($(val)); if (thisIndex < valIndex && valIndex < selIndex) { selIndex = valIndex; $result = $(val); } }); return $result; }; })(jQuery);
1
2
3
如果你可以使用IE9 +,你可以尝试compareDocumentPosition()
。 一个简单的jQuery插件看起来像这样:
$.fn.below = function(selector) { var el = this[0], compare = $(selector), nextEl; compare.each(function(i, item) { var result = el.compareDocumentPosition(item); // get the first one that appears below `this` if (result === 4) { nextEl = $(item); return false; } }); return nextEl || $(); };
这可能会被清理/简化一点。 但它很好用。 这是一个docker:
http://codepen.io/ZevanRosser/pen/QbjZmr?editors=101
compareDocumentPosition()
返回一个具有以下含义的数字:
(其中p1.compareDocumentPosition(p2)
)
1:没有关系,两个节点不属于同一个文件。
2:第一节点(p1)位于第二节点(p2)之后。
4:第一节点(p1)位于第二节点(p2)之前。
8:第一节点(p1)位于第二节点(p2)内。
16:第二节点(p2)位于第一节点(p1)内。
32:没有关系,或者两个节点是同一元素上的两个属性。
请注意,以上内容仅限于: http : //www.w3schools.com/jsref/met_node_comparedocumentposition.asp