检查元素是否在jQuery中的另一个元素之前或之后 [英] Check if element is before or after another element in jQuery
问题描述
让我们假设我有这个标记
< h3 id =first> First< / h3>
< p> Hi< / p>
< p> Hello< / p>
< h3 id =second> Second< / h3>
< p>再见< / p>
< p>再见< / p>
如何以编程方式检查元素,例如 p
s,是在第一个 h3
之后,在第二个 h3
之前,使用jQuery? p>
我正在尝试这样做:
$(p) .each(function(){
if($(this).isAfter(#first)&& $(this).isBefore(#second)){
// do东西
}
});
要查看元素是否相继,您可以请使用 prev()
或 prevAll()
以获取上一个元素,以及看看它是否匹配。
要查看一个元素是否在另一个之前,您可以使用 next()
或 nextAll()
以获取下一个元素,并查看它是否匹配。
$。fn.isAfter = function(sel){
return this.prevAll(sel).length!== 0;
}
$ .fn.isBefore = function(sel){
return this.nextAll(sel).length!== 0;
}
演示: http://jsfiddle.net/bk4k7/
Let us suppose I have this markup
<h3 id="first">First</h3>
<p>Hi</p>
<p>Hello</p>
<h3 id="second">Second</h3>
<p>Bye</p>
<p>Goodbye</p>
How can I programmatically check if an element, such as one of the p
s, is after first h3
and before the second h3
, with jQuery?
I am trying to do something like this:
$(p).each(function(){
if($(this).isAfter("#first") && $(this).isBefore("#second")) {
// do stuff
}
});
To see if an element is after another, you can use prev()
or prevAll()
to get the previous element(s), and see if it matches.
And to see if an element is before another, you can use next()
or nextAll()
to get the next element(s), and see if it matches.
$.fn.isAfter = function(sel){
return this.prevAll(sel).length !== 0;
}
$.fn.isBefore= function(sel){
return this.nextAll(sel).length !== 0;
}
DEMO: http://jsfiddle.net/bk4k7/
这篇关于检查元素是否在jQuery中的另一个元素之前或之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!