尝试这个。它将标记您的元素,创建一组与您的选择器匹配的元素,并从您的元素后面的集合中收集所有元素。
$.fn.findNext = function ( selector ) {
var set = $( [] ), found = false;
$( this ).attr( "findNext" , "true" );
$( selector ).each( function( i , element ) {
element = $( element );
if ( found == true ) set = set.add( element )
if ( element.attr("findNext") == "true" ) found = true;
})
$( this ).removeAttr( "findNext" )
return set
}
编辑
使用 jquerys 索引方法更简单的解决方案。你调用方法的元素需要被同一个选择器选择
$.fn.findNext = function( selector ){
var set = $( selector );
return set.eq( set.index( this, ) + 1 )
}
为了摆脱这个障碍,我们可以使用浏览器自己的compareDocumentposition
$.fn.findNext = function ( selector ) {
// if the stack is empty, return the first found element
if ( this.length < 1 ) return $( selector ).first();
var found,
that = this.get(0);
$( selector )
.each( function () {
var pos = that.compareDocumentPosition( this );
if ( pos === 4 || pos === 12 || pos === 20 ){
// pos === 2 || 10 || 18 for previous elements
found = this;
return false;
}
})
// using pushStack, one can now go back to the previous elements like this
// $("#someid").findNext("div").remove().end().attr("id")
// will now return "someid"
return this.pushStack( [ found ] );
},
编辑 2
使用 jQuery 的 $.grep 更容易。这是新代码
$.fn.findNextAll = function( selector ){
var that = this[ 0 ],
selection = $( selector ).get();
return this.pushStack(
// if there are no elements in the original selection return everything
!that && selection ||
$.grep( selection, function( n ){
return [4,12,20].indexOf( that.compareDocumentPosition( n ) ) > -1
// if you are looking for previous elements it should be [2,10,18]
})
);
}
$.fn.findNext = function( selector ){
return this.pushStack( this.findNextAll( selector ).first() );
}
当压缩变量名时,这变成了仅仅两个班轮。
编辑 3
使用按位运算,这个函数可能更快?
$.fn.findNextAll = function( selector ){
var that = this[ 0 ],
selection = $( selector ).get();
return this.pushStack(
!that && selection || $.grep( selection, function(n){
return that.compareDocumentPosition(n) & (1<<2);
// if you are looking for previous elements it should be & (1<<1);
})
);
}
$.fn.findNext = function( selector ){
return this.pushStack( this.findNextAll( selector ).first() );
}