【问题标题】:jQuery find next/prev elements of a certain class but not necessarily siblingsjQuery查找某个类的下一个/上一个元素,但不一定是兄弟
【发布时间】:2010-12-22 02:22:46
【问题描述】:

next、prev、nextAll 和 prevAll 方法非常有用,但如果您要查找的元素不在同一个父元素中,则不然。我想做的是这样的:

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

当按下 id click 的 span 时,我想将下一个元素与 find 类匹配,在这种情况下,它不是被点击元素的兄弟,所以 next()nextAll() 赢了不行。

【问题讨论】:

标签: jquery jquery-selectors next


【解决方案1】:

试试这个。它将标记您的元素,创建一组与您的选择器匹配的元素,并从您的元素后面的集合中收集所有元素。

$.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() );
}

【讨论】:

  • 我没有想到的一个缺点是,您从中调用 findNext 的元素需要由同一个选择器选择,否则它将简单地循环遍历所有内容而找不到您标记的元素。
  • 谢谢你,我已经看遍了,没有人能像你一样简洁地回答非兄弟姐妹的情况。
  • 感谢您的工作。对于非常大的表格文档,Edit 2 将我试图做的事情加快了几个数量级!
  • @allicarn 查看我的最新编辑。按位运算肯定比 $.inArray 中使用的循环更快
  • 抱歉...compareDocumentPosition 似乎也存在问题:“注意:Internet Explorer 8 及更早版本不支持此方法。”我想我在实现 $.inArray 后没有正确测试它
【解决方案2】:

我今天自己正在解决这个问题,这是我想出的:

/**
 * 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');

我怀疑它在大型结构上是否会表现良好,但在这里:)

【讨论】:

  • 如果您要选择的元素是同级元素,则不起作用。它声明了全局变量“hay”。
  • 谁会修改这个来找到上一个?
  • 写得很好!
【解决方案3】:

我的解决方案将涉及稍微调整您的标记以使 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...
    });
});

这使您可以灵活地在我建议的包装器中使用任何类型的标记和层次结构,并且仍然可以可靠地找到您的目标。

祝你好运!

【讨论】:

    【解决方案4】:

    我认为解决这个问题的唯一方法是对当前元素之后的元素进行递归搜索。 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>
    

    【讨论】:

      【解决方案5】:

      下面的表达式应该(除非语法错误!)找到包含p.find元素的父元素的所有兄弟元素,然后找到那些p.find元素并将它们的颜色更改为蓝色。

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

      当然,如果您的页面结构使得p.find 出现在完全不同的层次结构级别(例如祖父母的兄弟姐妹),则它不会起作用。

      【讨论】:

        猜你喜欢
        • 2019-12-21
        • 2014-07-12
        • 2013-12-23
        • 2017-06-02
        • 2014-07-16
        • 1970-01-01
        • 1970-01-01
        • 2013-05-29
        • 1970-01-01
        相关资源
        最近更新 更多