With jQuery (or javascript), how can I have one button reveal different hidden (display: none) divs with each click? For example, on the first click of the button, div1 should appear. On the second click of the same button, div2 will appear also (so both div1 and div2 are visible). Same for div3, etc.

With the code I have now, the first button click reveals all the hidden divs at once. Here's an example:

$(document).ready(function () {
    $('button').click(function () {
        $('.div1').show('slow');
    });
    $('button').click(function () {
        $('.div2').show('slow');
    });
    $('button').click(function () {
        $('.div3').show('slow');
    });
});
有帮助吗?

解决方案

The reason they are all appearing at once is because what you have done now is appended three separate click handlers to the same object that each show in a separate div. Now every time you click on "button", all three of those functions are going to run.

What you could do is collect all the divs you want to show in one object, and keep a count of the amount of divs you have already shown in.

var count = 0,
    $allDivs = $('.div1, .div2, .div3');

$('.button').click( function() {
    if( count < $allDivs.length - 1 ) {
        $allDivs.eq( count ).show( 'slow' );
        count++;
    }
});

If you select all the divs at once, then you can use jQuery's eq() method to pick them out one at a time.

Here is a working example on JS fiddle: http://jsfiddle.net/grammar/76arV/

Hope this helps!

其他提示

var blocks = $('.div1, .div2, .div3');
$('button').click(function () {
    if (block = blocks.next())
        block.show('slow');
});

What about this?

var iShow = 0;
$('button').click(function () {
    $('.show:eq(' + iShow + ')').show('slow');
    iShow = iShow + 1;
});

So in this example i gave every element that you want to interact with the button the class .show. This way you can just select any of these element by the index value, you do this with .eq().
First .show element has the index value of 0, so that is where we start(our default value). Each time we click we increasing the variable by one so next there is clicked, the next element will be showed.


Based on what you want to do next, you can do the same with hiding all the elements again one by one. Hope this helped you.

jsFiddle

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top