0

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

(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' 内切换类('.active')和 removeClass('.active')

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

4

1 回答 1

1

这是一个适当的逻辑难题,但我认为我已经成功了(如果我误解了,请告诉我):

JSFiddle

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

var active = $('.active');

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

...您不想执行使兄弟姐妹向上滑动并切换active类的链。

我还调整了activate功能,如下所述:

function activate(el,effect){

    //only do this if no effect is specified (i.e. don't do this on the first pass)
    if (!effect) {
        $(el)
             .toggleClass('active') //first toggle the class of the clicked element (i.e. 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);
}
于 2013-06-02T17:28:17.823 回答