How do I remove class from previous selection when

2019-08-30 18:41发布

http://jsfiddle.net/freqn/ZHt6V/2/

How do I remove class from previous selection when clicking additonal item in this accordion? I want the class to be removed from the previous clicked item when the next item is expanded. All other items should turn back to gray when new item is selected. Thank you.

(function () {

    $('dd').hide();
    $('dt').click(function(){
        $(this)
            .next()
            .slideToggle(200)
            .siblings('dd')
            .slideUp(200);
        });   

    $('dt').click(function(){
        $(this).toggleClass('active');

    }); 

})();

1条回答
女痞
2楼-- · 2019-08-30 19:02

Edit: http://jsfiddle.net/uptownapps/ZHt6V/5/ -- Revision to add collapse functionality.

http://jsfiddle.net/uptownapps/ZHt6V/4/

First you can use the same click function to handle all of this. Also, I prefer to use removeClass and addClass rather than toggleClass just because I am able to keep track of what's happening in my head better that way.

    (function () {

    $('dt').click(function(){
        $(this) .next()
                .slideToggle(200)
                .siblings('dd')
                .slideUp(200);

        $('.active').removeClass('active');
        $(this).addClass('active');
    });

})();

You'll notice I also removed the $('dd').hide(); and instead added display: none; to the CSS definition for the dd element. This will fix the "flash" you see when the page loads before jQuery and your JS has run.

查看更多
登录 后发表回答