20

next、prev、nextAll、およびprevAllメソッドは非常に便利ですが、検索しようとしている要素が同じ親要素にない場合はそうではありません。私がやりたいのは次のようなものです。

<div>
    <span id="click">Hello</span>
</div>
<div>
    <p class="find">World></p>
</div>

idのスパンclickが押されたときに、次の要素をクラスと一致させたいのですがfind、この場合、クリックされた要素の兄弟ではないnext()か、機能しnextAll()ません。

4

5 に答える 5

15

これを試して。要素にマークを付け、セレクターに一致する要素のセットを作成し、要素に続くセットからすべての要素を収集します。

$.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() );
}
于 2012-09-10T15:19:56.590 に答える
8

私は今日この問題に自分で取り組んでいました、これが私が思いついたものです:

/**
 * Find the next element matching a certain selector. Differs from next() in
 *  that it searches outside the current element's parent.
 *  
 * @param selector The selector to search for
 * @param steps (optional) The number of steps to search, the default is 1
 * @param scope (optional) The scope to search in, the default is document wide 
 */
$.fn.findNext = function(selector, steps, scope)
{
    // Steps given? Then parse to int 
    if (steps)
    {
        steps = Math.floor(steps);
    }
    else if (steps === 0)
    {
        // Stupid case :)
        return this;
    }
    else
    {
        // Else, try the easy way
        var next = this.next(selector);
        if (next.length)
            return next;
        // Easy way failed, try the hard way :)
        steps = 1;
    }

    // Set scope to document or user-defined
    scope = (scope) ? $(scope) : $(document);

    // Find kids that match selector: used as exclusion filter
    var kids = this.find(selector);

    // Find in parent(s)
    hay = $(this);
    while(hay[0] != scope[0])
    {
        // Move up one level
        hay = hay.parent();     
        // Select all kids of parent
        //  - excluding kids of current element (next != inside),
        //  - add current element (will be added in document order)
        var rs = hay.find(selector).not(kids).add($(this));
        // Move the desired number of steps
        var id = rs.index(this) + steps;
        // Result found? then return
        if (id > -1 && id < rs.length)
            return $(rs[id]);
    }
    // Return empty result
    return $([]);
}

だからあなたの例では

<div><span id="click">hello</span></div>
<div><p class="find">world></p></div>

これで、次を使用して「p」要素を見つけて操作できます。

$('#click').findNext('.find').html('testing 123');

大きな構造物でうまく機能するとは思えませんが、ここにあります:)

于 2010-11-07T23:08:04.620 に答える
4

私の解決策は、jQueryをはるかに簡単にするために、マークアップを少し調整することです。これが不可能であるか、魅力的な答えでない場合は、無視してください。

私はあなたがやりたいことの周りに「親」ラッパーをラップします...

<div class="find-wrapper">
    <div><span id="click">hello</span></div>
    <div><p class="find">world></p></div>
</div>

今、見つけるためにfind

$(function() {
    $('#click').click(function() {
        var $target = $(this).closest('.find-wrapper').find('.find');
        // do something with $target...
    });
});

これにより、私が提案したラッパー内に任意の種類のマークアップと階層を設定し、それでも確実にターゲットを見つけることができる柔軟性が得られます。

幸運を!

于 2009-12-03T06:11:43.900 に答える
0

この問題を解決する唯一の方法は、現在の要素の後にある要素を再帰的に検索することだと思います。jQueryによって提供されるこの問題に対する簡単な解決策はありません。親要素の兄弟内の要素のみを検索する場合(例の場合のように)、再帰検索を実行する必要はありませんが、複数の検索を実行する必要があります。

私はあなたが望むことをする例(実際には再帰的ではありません)を作成しました(私は願っています)。現在クリックされている要素の後のすべての要素を選択し、それらを赤にします。

<script type="text/javascript" charset="utf-8">
    $(function () {
        $('#click').click(function() {
            var parent = $(this);
            alert(parent);
            do {
                $(parent).find('.find').css('background-color','red'); 
                parent = $(parent).parent();
            } while(parent !== false);
        });
    });
</script>
于 2009-12-01T17:34:54.867 に答える
0

次の式は、(構文エラーを除いて)要素を含む親のすべての兄弟を検索しp.find、次にそれらのp.find要素を検索して、それらの色を青に変更する必要があります。

$(this).parent().nextAll(":has(p.find)").find(".find").css('background-color','blue');

もちろん、ページ構造がp.findまったく異なるレベルの階層(たとえば、祖父母の兄弟)で発生するようなものである場合、それは機能しません。

于 2009-12-01T18:11:12.700 に答える