jquery多层手风琴

我有简单的多级手风琴插件。 这对我来说几乎是完美的。

(function(jQuery){ jQuery.fn.extend({ accordion: function() { return this.each(function() { var $ul = $(this); if($ul.data('accordiated')) return false; $.each($ul.find('ul, li>div'), function(){ $(this).data('accordiated', true); $(this).hide(); }); $.each($ul.find('a'), function(){ $(this).click(function(e){ activate(this); return void(0); }); }); var active = $('.active'); if(active){ activate(active, 'toggle'); $(active).parents().show(); } function activate(el,effect){ $(el).parent('li').toggleClass('active').siblings().removeClass('active').children('ul, div').slideUp('fast'); $(el).siblings('ul, div')[(effect || 'slideToggle')]((!effect)?'fast':null); } }); } }); })(jQuery); 

完整代码 – http://jsfiddle.net/SKfax/

我试图稍微重新制作这段代码,但没有任何成功。 我需要在’a’元素内部而不是它们的父’li’中的toggleClass(’。active’)和removeClass(’。active’)

PS:’。active’类仅适用于当前打开的部分的标题。

这是一个恰当的逻辑难题,但我认为我已经有了它的工作(如果我误解了,请告诉我):

的jsfiddle

我认为关键是要防止activate函数中的第一个链在第一次传递时运行。 所以当你在这里打电话时:

 var active = $('.active'); if(active){ activate(active, 'toggle'); $(active).parents().show(); } 

…你不想执行滑动兄弟姐妹的链并切换active类。

我还调整了activatefunction,如下所述:

 function activate(el,effect){ //only do this if no effect is specified (ie don't do this on the first pass) if (!effect) { $(el) .toggleClass('active') //first toggle the class of the clicked element (ie the 'a' tag) .parent('li') //now we go up the DOM to the parent 'li' .siblings() //get the sibling li's .find('a') //get the 'a' tags below them (assuming there are no 'a' tags in the content text!) .removeClass('active') //remove active class from these 'a' tags .parent('li') .children('ul, div') .slideUp('fast'); //and hide the sibling content } //I haven't touched this $(el).siblings('ul, div')[(effect || 'slideToggle')]((!effect)?'fast':null); }