jQuery查找特定类的下一个/上一个元素,但不一定是同级 [英] jQuery find next/prev elements of a certain class but not necessarily siblings

查看:181
本文介绍了jQuery查找特定类的下一个/上一个元素,但不一定是同级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The next, prev, nextAll and prevAll methods are very useful, but not if the elements you are trying to find are not in the same parent element. What I want to do is something like this:

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

当按下id为click的跨度时,我想将下一个元素与类find匹配,在这种情况下,该元素不是单击元素的同级,所以 不起作用.

When the span with the id click is pressed, I want to match the next element with the class find, which in this case is not a sibling of the clicked element so next() or nextAll() won't work.

推荐答案

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

I was working on this problem myself today, here's what I came up with:

/**
 * 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>

您现在可以使用

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

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

I doubt it will perform well on large structures, but here it is :)

这篇关于jQuery查找特定类的下一个/上一个元素,但不一定是同级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆