开发者

Jquery showing div one by one

let say i have 10 div's with same id now 9 of those are hidden on page on and only one is visi开发者_运维技巧ble , what i want is once a person will click the next button it should hide the 1st one and shows the next just after it and so on, problem is that they all have same id's so how to can i achieve that

Need some help Thanks


Here's another way without using a counter. This also correctly handles cycling to the first div after the last.

Working Demo

$('#next').click(function() {
    var $shownDiv = $('div.content').not('.hidden');
    if ($shownDiv.next('.hidden').length === 0) {
        $('div.hidden:first').removeClass('hidden').show();
    } else {
        $shownDiv.next('.hidden').removeClass('hidden').show();
    }
    $shownDiv.addClass('hidden').hide();
});


Firstly you shouldn't be using the same id for multiple elements on your page.

Go with classes instead. <div class="myclass">.

If you're using a next button, one thing you can do is keep a count of where you're upto in the array of elements with your class, hide all elements of that class and show the one with the index you're at.

I'll whip up a quick demo for you.

Update

Here's a very basic demo example you for: http://jsfiddle.net/SENqj/

var item0 = $(".myItems").first().show();
var counter = 1;

$("#toggler").click(function(){
    $(".myItems").hide();
    var currentItem = $('.myItems').get(counter);
    $(currentItem).show();
    counter++;
});

Update 2:

To ensure cycling of the items just include this one line in the click hander above:

counter = (counter < $(".myItems").length)? counter : 0;


I'm not sure if the given answers are a better solution, but I guess so. I spent the last minutes coming up with this one.

<html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.3.min.js"></script>

        <script type="text/javascript">
        function next_page() {

            // make new page part active
            $( ".active_part" ).next( ".hidden_page_part" ).addClass( "active_part" ).removeClass( "hidden_page_part" );;

            // disable first page part (make it non-active)
            $( ".active_part" ).first().removeClass( "active_part" ).addClass( "hidden_page_part" );
        }
        </script>

        <style type="text/css">
        .hidden_page_part {
            display: none;
            visibilty: hidden;
        }
        </style>
    </head>
    <body>
        <div>
            <div class="active_part">Show me 1st</div>
            <div class="hidden_page_part">Show me 2nd</div>
            <div class="hidden_page_part">Show me 3rd</div> 
            <div class="hidden_page_part">Show me 4th</div>
        </div>

        <input type="button" value="Next" onclick="next_page();" />
    </body>
</html>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜