jQuery 找到下一个不是立即的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/441687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find the next element that is not immediate?
提问by Logan Serman
I want to find the first span element after class counter, in code something like this:
我想在类计数器之后找到第一个 span 元素,代码如下:
<div class="counter"></div>
<p></p>
<span></span>
It seems like the next() function only finds the immediate next element, so something like this:
似乎 next() 函数只能找到紧邻的下一个元素,所以是这样的:
$(".counter").next("span")
Won't work. The way I have been using is a bit lengthy and I was wondering if there was a shorter way, it is this:
不会工作。我一直使用的方式有点冗长,我想知道是否有更短的方式,是这样的:
$(".counter").nextAll("span").eq(0)
I think the closest()
method in jQuery 3 will do the trick, but I am using 1.2.6 -- is there a better way to do this (am I just using next()
wrong?)
我认为closest()
jQuery 3 中的方法可以解决问题,但我使用的是 1.2.6 —— 有没有更好的方法来做到这一点(我只是用next()
错了吗?)
采纳答案by Pim Jager
I think your method is the best way. And if you feel it doesn't look good just turn it into a plugin:
我认为你的方法是最好的方法。如果你觉得它不好看,就把它变成一个插件:
jQuery.fn.firstAfter = function(filter){
return this.nextAll(filter).eq(0);
}
回答by Nick Olsen
Similar to the marked answer but looks a little cleaner using the :first selector:
类似于标记的答案,但使用 :first 选择器看起来更简洁:
$('.counter').nextAll('span:first')
回答by Andrew Hare
I think the siblings()
function is what you are looking for. Try something like this:
我认为该siblings()
功能正是您要寻找的。尝试这样的事情:
$(".counter").siblings("span");
回答by Allain Lalonde
I'm not sure that the closest method will do the trick, but if so... maybe you can extract the closest method from 1.3 and turning it into a plugin?
我不确定最接近的方法是否能奏效,但如果是这样……也许您可以从 1.3 中提取最接近的方法并将其转换为插件?
I haven't had a chance to try this, but give it a shot. It can't hurt:
我还没有机会尝试这个,但试一试。它不能伤害:
(function($) {
$.fn.closest = function (selector) {
return this.map(function(){
var cur = this;
while ( cur && cur.ownerDocument ) {
if ( $(cur).is(selector) )
return cur;
cur = cur.parentNode;
}
});
}
})(jQuery);
回答by landyman
Try something like this:
尝试这样的事情:
$(".counter ~ span:first");
Hope that helps!
希望有帮助!
回答by landyman
$(".counter + span")
$(".counter + span")