简体   繁体   English

如何在jQuery中切换所有未选中的元素

[英]How to toggle all but selected elements in jquery

I am trying to do the following: 我正在尝试执行以下操作:

  • There are multiple "title" and "text" divs on a page. 一个页面上有多个“标题”和“文本” div。
  • Upon loading the page only the first text is visible. 加载页面后,仅第一个文本可见。
  • When clicking on any title, its text slides down and all other texts slide up. 单击任何标题时,其文字向下滑动,所有其他文字向上滑动。

So far I came up with the following: HTML: 到目前为止,我提出了以下内容:HTML:

<div class="row clearfix">
    <div class="title"></div>
    <div class="text"></div>
</div>
<div class="row clearfix">
    <div class="title"></div>
    <div class="text"></div>
</div>
<div class="row clearfix">
    <div class="title"></div>
    <div class="text"></div>
</div>
<div class="row clearfix">
    <div class="title"></div>
    <div class="text"></div>
</div>

jQuery: jQuery的:

$('.title').click(function () {
    $(this).next().slideToggle();
})

https://jsfiddle.net/e3okos3e/ https://jsfiddle.net/e3okos3e/

However, this is very basic. 但是,这是非常基本的。

Can you tell me how to select every text other than the selected title's one? 您能告诉我如何选择除所选标题以外的所有文本吗? How to make only the first one visible at loading? 如何在加载时仅显示第一个?

So, if all of the text divs are hidden by default, then do this: 因此,如果默认情况下隐藏所有text div,请执行以下操作:

 $(document).ready(function(){ $('.title').click(function () { $('.active').slideToggle().removeClass('active'); $(this).next().slideToggle().addClass('active'); }) }); 
 .title { width: 100px; height: 20px; border: 1px solid #cc0; } .text { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row clearfix"> <div class="title"></div> <div class="text">text1</div> </div> <div class="row clearfix"> <div class="title"></div> <div class="text">text2</div> </div> <div class="row clearfix"> <div class="title"></div> <div class="text">text3</div> </div> <div class="row clearfix"> <div class="title"></div> <div class="text">text4</div> </div> 

Fairly straightforward using not() 使用not()相当简单

var $text = $('.text');// cache elements

$('.title').click(function () {
    var $next = $(this).next().slideDown();// or slideToggle()
    $text.not($next).slideUp();
});

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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