gpt4 book ai didi

javascript - 如何使 Accordion 事件项目可点击

转载 作者:行者123 更新时间:2023-11-29 22:06:42 26 4
gpt4 key购买 nike

在过去几个小时的反复试验之后,我意识到我真的应该学习 jQuery 基础知识的类(class)。有人可以帮助我给出一个可能很简单的答案吗?

我正在输入 this Accordion 进入页面,但我希望事件面板能够单击关闭。我可以做一些简单的事情来实现它吗?

(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com