简单 jQuery 手风琴切换

Simple jQuery accordion toggle

我正在使用 jQuery 制作一个带有切换状态的简单手风琴。到目前为止一切顺利,但是当我点击一个与我在开始时点击的初始切换不同的切换时,它会自行切换,使前一个切换处于打开状态。

如何进行某种检查以查看是否有另一个打开并切换其状态?

这是一个 Fiddle. 随便弄几秒钟,你就会明白我的意思了。

// Accordion init
// Hide accordion content on load
$('.accordion-content').hide();
$('.widget-accordion').find('.accordion-toggle').click(function() {

  // State change visuals
  $(this).toggleClass('opened');

  //Expand or collapse this panel
 $(this).next().slideToggle('fast');

  //Hide the other panels
  $(".accordion-content").not($(this).next()).slideUp('fast');

});

正如我在上面的评论中所述,这是一个有效的 fiddle。

问题是,当您打开一个手风琴项目时,不允许打开其他项目,这意味着您必须清除每个 class 代表状态打开...

Working Fiddle

// Accordion init
// Hide accordion content on load
$('.accordion-content').hide();
$('.widget-accordion').find('.accordion-toggle').click(function() {
    $('.accordion-toggle').not(this).each(function(){
    $(this).removeClass("opened");
  });
  // State change visuals
  $(this).toggleClass('opened');

  //Expand or collapse this panel
  $(this).next().slideToggle('fast');

  //Hide the other panels
  $(".accordion-content").not($(this).next()).slideUp('fast');

});

用这个代替 toggleClass:

// State change visuals
 $('.accordion-toggle').removeClass('opened');
 $(this).addClass('opened');

Fiddle: https://jsfiddle.net/cndnnww5/5/