开发者

jquery show next div of same class?

I have a bunch of div's like

            <div class="slides">
                <div id="box_bg">
                    <div class="previous"></div>
                    <img src="images/minido_pic.png" width="267" height="252" alt="MiniDo" class="img1" />
                    <div class="next"></div>
                </div>
                <div id="text1">
                    <p>MiniDo - Adobe Air App - Simplistic design wrapped aro开发者_如何学Cund a simple iOS style window built for the Windows environment using Adobe Air.</p>
                </div>
            </div>

and a bunch of jquery

$(document).ready(function(){   
    $(".slides").hide();

        var length = $(".slides").length;
        var ran = Math.floor(Math.random()*length);
        $(".slides:nth-child(" + ran + ")").show();

    $('.previous').click(function() {
        $(".slides").parentsUntil(".slides").prev().show();
        $('.slides').hide();
    });

    $('.next').click(function() {
        $(this).parentsUntil(".slides").next().show();
        $('.slides').hide();
    });
});

Now what I want to so is on page load, show a random ".slides" which works fine. And then when a user presses ".next" or ".previous" it loads the next ".slides".

However I can't seem to get it to work? When I press next or previous it shows nothing?

Any help?


You should use

for previous

$(this).closest('.slides').prevAll('.slides').eq(0).show();

and for next

$(this).closest('.slides').nextAll('.slides').eq(0).show();

And the most important is to hide the .slides before you show the next one.

So the $('.slides').hide(); should be before the .show() commands otherwise, you just show the one you want and then hide all (including the one you just showed)


Altogether

$('.previous').click(function() {
    $('.slides').hide();
    var previous = $(this).closest('.slides').prevAll('.slides').eq(0);
    if (previous.length === 0) previous = $(this).closest('.slides').nextAll('.slides').last();
    previous.show();
});

$('.next').click(function() {
    $('.slides').hide();
    var next = $(this).closest('.slides').nextAll('.slides').eq(0);
    if (next.length === 0) next = $(this).closest('.slides').prevAll('.slides').last();
    next.show();
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜