jQuery切换 - 关闭除此之外的所有内容 [英] jQuery toggle - Close all except this

查看:294
本文介绍了jQuery切换 - 关闭除此之外的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我的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;
}

我可以根据需要切换它。



问题

当我点击切换类时,我想关闭所有打开的容器类但是不切当前的容器类(因为它应该被切换)。



当前容器类应该切换。这意味着所有元素都可以关闭,但只能同时打开一个元素。



我试图在脚本之前隐藏jQuery,但这使得容器 - 类不可能关闭(因为当切换隐藏等于显示)。



代码猜测 隐藏所有.container, em>

使用 David's answer 作为起点,我们可以使用 .siblings 来完成您想要的任务:

  $ ('.toggle')。click(function(){
var index = $(this).index(); $ b $('。container')。eq(index).toggle()。兄弟姐妹('。container')。hide();
});

请参阅: http://www.jsfiddle.net/85zCp/






作为除此之外,您可能希望使用JavaScript最初隐藏所有元素而不是CSS,因为禁用JavaScript的用户在使用CSS隐藏它们时将无法看到任何内容。另外,您可能希望每个 h4 标题都放在内容的前面,而不是像现在这样放在一起。

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.

这篇关于jQuery切换 - 关闭除此之外的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆