简体   繁体   中英

jQuery toggle - Close all except this

I have found this code (jQuery):

$('.toggle').click(function() {
    $('.container').eq($(this).index()).toggle('fast');
});

This is my HTML:

<h4 class="toggle">Title1</h4>
<h4 class="toggle">Title2</h4>
<h4 class="toggle">Title3</h4>
<div class="container">Content1</div>
<div class="container">Content2</div>
<div class="container">Content3</div>

CSS

.container {
   display: none;
}

I can toggle what I want with it.

The problem

When I click the toggle-class I want to close all open container-classes BUT NOT the current container-class (because it should be toggled).

The current container-class should toggle. That means that all elements could be closed BUT ONLY ONE could be opened at the same time.

I tried to just put jQuery hide before the script but that makes the container-class impossible to close (because when toggle hide is equal to show).

Code guess hide all .container except this

Using David's answer as a starting point, we can use .siblings to accomplish what you want:

$('.toggle').click(function() {
    var index = $(this).index();
    $('.container').eq(index).toggle().siblings('.container').hide();
});

See: http://www.jsfiddle.net/85zCp/


As an aside, you might want to use JavaScript to hide all elements initially instead of CSS because users with JavaScript disabled won't be able to see any content if you use CSS to hide them. Also, you would probably want to have each h4 heading in front of the contents instead of it put together like you're doing right now.

$('.toggle').click(function () { $('.container').hide('fast'); $('.container').eq($(this).index()).show('fast'); });

I don't know exactly but I think this is what you're looking for...

Cheers...

This is a little verbose, but its use should be fairly obvious:

$('.toggle').click(
    function(){
        var index = $(this).index();
        $('.container').hide().eq(index).show();
    });

JS Fiddle demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM