How do I remove class from previous selection when clicking additional item?

心不动则不痛 提交于 2019-12-14 03:17:18

问题


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:


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.



来源:https://stackoverflow.com/questions/20025799/how-do-i-remove-class-from-previous-selection-when-clicking-additional-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!