【问题标题】:How to make accordion active item clickable如何使手风琴活动项目可点击
【发布时间】:2013-12-15 23:50:35
【问题描述】:

在过去几个小时的反复试验之后,我意识到我真的应该学习 jQuery 基础知识的课程。有人可以帮我解答一个简单的问题吗?

我将this 手风琴放入页面,但我希望活动面板能够单击以关闭。有什么简单的方法可以让这成为可能吗?

(function($) {

  //Hide all panels
  var allPanels = $('.accordion > dd').hide();

  //Show first panel
  $('.accordion > dd:first-of-type').show();

  //Add active class to first panel 
  $('.accordion > dt:first-of-type').addClass('accordion-active');

  //Handle click function
  jQuery('.accordion > dt').on('click', function() {

    //this clicked panel
    $this = $(this);

    //the target panel content
    $target = $this.next();

    //Only toggle non-displayed 
    if(!$this.hasClass('accordion-active')){

      //slide up any open panels and remove active class
      $this.parent().children('dd').slideUp();

      //remove any active class
      jQuery('.accordion > dt').removeClass('accordion-active');

      //add active class
      $this.addClass('accordion-active');

      //slide down target panel
      $target.addClass('active').slideDown();

    }

    return false;
  });

})(jQuery);

【问题讨论】:

    标签: javascript jquery wordpress accordion


    【解决方案1】:

    试试:

      jQuery('.accordion > dt').on('click', function() {
          //this clicked panel
          var $this = $(this), 
              $target = $this.next(); 
    
          //slide up any open panels and remove active class
          $this.parent().children('dd').not($target).slideUp(); //Slide Up everything but the target one
    
          //remove any active class
          jQuery('.accordion > dt').removeClass('accordion-active');
          //add active class
          $this.addClass('accordion-active');
          //slide down target panel
          $target.addClass('active').slideToggle();
    
        return false;
      });
    

    Demo

    实际上您可以将其简化为:

     jQuery('.accordion > dt').on('click', function () {
            var $this = $(this) ,
                $target = $this.next();
    
            $('.accordion > dt.accordion-active').not($this.toggleClass('accordion-active')).removeClass('accordion-active');
    
            $this.siblings('dd').not($target.addClass('active').slideToggle()).slideUp();
    
            return false;
        });
    

    Demo

    【讨论】:

    • 也许我错了,但....parent().children('dd') 不是.siblings('dd') 的更长表达方式吗?我不经常使用它,所以我真的很好奇
    • 精彩。感谢 PSL 和 Deryck。像魅力一样工作!
    • 更好!谢谢:)
    猜你喜欢
    • 2022-01-26
    • 2016-06-29
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    相关资源
    最近更新 更多