经过最后几个小时的反复试验,我意识到我确实应该学习有关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);
最佳答案
尝试:
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
关于javascript - 如何使 Accordion 事件项目可点击,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20601426/