在过去几个小时的反复试验之后,我意识到我应该学习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);
答案 0 :(得分:2)
尝试:
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 强>