jquery list item class toggle

后端 未结 5 2140
悲哀的现实
悲哀的现实 2021-02-11 08:19

I have a simple function to toggle list item class from \"active\" to \"inactive\". What is the most efficient way (i.e., using the least amount of code) to set all other list i

5条回答
  •  失恋的感觉
    2021-02-11 08:53

    This can work:

    $('.menu li').click(function () {
        $('.menu li').not(this).removeClass('active').addClass('inactive');
        $(this).addClass('active').removeClass('inactive');
    });
    

    or

    $('.menu li').click(function () {
        $('.menu li').removeClass('active').addClass('inactive');
        $(this).toggleClass('active inactive');
    });
    

    The second method is shorter, but slower.

    http://jsperf.com/toggle-vs-add-remove

    Edit: This one is shorter and faster:

    $('.menu li').click(function () {
        $('.menu li').not(this).removeClass('active');
        $(this).addClass('active');
    });
    

    If performance is really a problem you can store your menu in a variable and perform operations on this variable, like:

    var $menu = $('.menu li');
    $menu.click(function () {
            $menu.not(this).removeClass('active');
            $(this).addClass('active');
        });
    

提交回复
热议问题