如何仅切换* next *并隐藏其他类

我在可折叠的jquery中遇到了一些问题。

我的HTML元素是这样的

First Heading

First Section

First Section

First Section

Second Heading

Second Section

Second Section

Third Heading

Third Section

Second Section

我正在使用这个jquery来切换类

  $(document).ready(function () { $(".collapse").click(function () { $(this).toggleClass("active"); }); }); jQuery(document).ready(function() { jQuery(".accordion-active").hide(); //toggle the componenet with class msg_body jQuery(".collapse").click(function() { jQuery(this).next(".accordion-active").slideToggle(0); }); }); 

现在我的问题,当我点击第一个h1标签时,它只显示其elements.thats很好。 但是现在当我点击第二个h1标签时它显示了它的元素,但是第一个H1标签仍然打开。

当一个(下一个类)处于活动状态时,如何将所有其他人隐藏起来?

谢谢

试试这个。

 $(".accordion-active").hide(); //toggle the componenet with class msg_body $(".collapse").click(function(){ var $this = $(this); // Cacheing $(this) $('.accordion-active').slideUp(); if( !$this.next(".accordion-active").is('.open') ){ //$('h1').removeClass('active'); $('.accordion-active').removeClass('open'); $this.addClass("active").siblings("h1").removeClass("active"); $this.next(".accordion-active").addClass('open').slideDown(); } else { $("h1").removeClass("active"); $this.next(".accordion-active").removeClass('open').slideUp(); } }); 

小提琴演示

或者您可以使用Accordion – jQuery UI 。