找到DOM中稍后出现的下一个元素 [英] Find the next element that comes later in DOM
问题描述
在javascript中可能更好,但这肯定包括jQuery或任何这样的库。
Probably better in javascript, but this can sure include jQuery, or any such library.
我想找到第一个 .next
在下面的示例中。
I want to find the first .next
in the example below.
对于类似的问题有很多答案,建议 nextAll
或兄弟姐妹
......这两个都没用:
There are a lot of answers to similar questions that suggest nextAll
or siblings
... Both are useless here:
$(function(){
$('.result').text(
$('.origin').nextAll('.next').text()
|| $('.origin').siblings('.next').text()
|| 'both failed'
)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="whatever">
<p class="result"></p>
<p class="origin">1</p>
</div>
<p class="next">2</p>
<p class="next">3</p>
此外,什么是最兼容的(浏览器和库)聪明的)和大多数性能(速度和更少的代码行)方式这样做?
Also, what'd be the most compatible (browser and library wise) and most performatic (speed and less lines of code) way to do it so?
推荐答案
基于 @mrtsherman 的https://stackoverflow.com/a/8902127/274502>精彩答案 ,我写了这个更完整的解决方案并测试它在Chrome和Safari上工作:
Based on the awesome answer by @mrtsherman, I wrote this more complete solution and tested it to work on Chrome and 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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="whatever">
<p class="result"></p>
<p class="origin">1</p>
</div>
<p class="next">2</p>
<p class="next">3</p>
我可能尝试在jQuery lib上提交一个PR ,因为我相信 ...
I will probably try to submit a PR for this on jQuery lib, because I believe...
这应该是jQuery的核心方法! :P
事实上,我刚刚对此进行了一次非常简单的测试,对于这个简单的例子,它的表现甚至优于 nextAll
。几乎快两倍! :o
In fact, I just ran a very simplistic test on this, and it performed even better than nextAll
for this simple example. Almost twice as fast! :o
这篇关于找到DOM中稍后出现的下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!