これを試して。要素にマークを付け、セレクターに一致する要素のセットを作成し、要素に続くセットからすべての要素を収集します。
$.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() );
}
変数名を圧縮する場合、これは単なる2つのライナーになります。
ビット演算を使用して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() );
}