开发者

jQuery .nextUntil() equivalent

I need an alternative for jQuery's .nextUntil(). I'm currently using jQuery 1.3.1 and updating it is out of the question :(

I have this HTML:

<h4>...</h4>
<p>...</p>
<p>...</p>
<p>...</p>
<h4>...</h4>
<p>...</p>
<p>...</p>

and I have this jQuery code:

$('h4').click(function(){
    $(this).nextUntil('h4').toggl开发者_如何学Ce();
});

but .nextUntil() is added in 1.4.0 So do you have an idea how to do that in 1.3.1 ?


You can emulate the behavior of nextUntil() by using nextAll(), slice() and index() together:

var $nextAll = $(this).nextAll();
$nextAll.slice(0, $nextAll.index("h4")).toggle();


$('h4').click(function() {
    $(this).nextAll().each(function() {
        if ($(this).is('h4')) { return false; }
        $(this).toggle();
    })
});

Not tested. Tested by @ingo :)


Not tested, but something like this:

function nextUntil($start, until)
{
    var matches = [];

    for (var e = $start.next(); e.length !== 0 && !e.is(until); e = e.next())
    {
        matches.push(e);
    }
    return $(matches);
}

Or use nextAll():

function nextUntil_v2($start, until)
{
    var matches = [];

    $start.nextAll().each(function ()
    {
        if ($(this).is(until)) return false;
        matches.push(this);
    });

    return $(matches);
}


I did it like this

$('h4').click(function(){
    $n = $(this).next();
    while($n.is('h4') == false) {
        $n.toggle();
        $n = $n.next();
    }
});


If someone still needs to use jQuery 1.3: There is the jQuery Untils plugin, which got added to jQuery 1.4.0:

jQuery Untils provides three very simple, but very useful methods: nextUntil, prevUntil, and parentsUntil. These methods are based on their nextAll, prevAll, and parents counterparts, except that they allow you to stop when a certain selector is reached. Elements are returned in “traversal order”.

...

Tested with jQuery 1.3.2 in Internet Explorer 6-8, Firefox 2-3.7, Safari 3-4, Chrome 4-5, Opera 9.6-10.1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜