jquery list item class toggle

后端 未结 5 2137
悲哀的现实
悲哀的现实 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

    For brevity:

    $('ul.menu li').click(function () {
        $(this).siblings().attr('class', 'inactive').end().toggleClass('inactive active');
    });
    

    JS Fiddle demo (127 characters, whitespace-removed character-count: 115).

    Character-counts at JS Fiddle, since brevity was the intent, it seems.

    Unfortunately, given the problem identified in the comments, below, a corrected implementation is somewhat more verbose than the (currently-accepted answer), alternatives being:

    $('ul.menu li').click(function () {
        var t = this;
        $(this).siblings().add(t).attr('class', function (){
            return t === this ? 'active' : 'inactive';
        });
    });
    

    JS Fiddle demo (174 characters, whitespace-removed character-count: 133).

    Or:

    $('ul.menu li').click(function () {
        var t = this;
        $(this).parent().children().attr('class', function (){
            return t === this ? 'active' : 'inactive';
        });
    });
    

    JS Fiddle demo (176 characters, whitespace-removed character-count: 135).

    Of course, white space-removed jQuery does become somewhat unreadable, but still: I claim the, uh, moral victory...

    References:

    • add().
    • attr().
    • children().
    • end().
    • siblings().
    • toggleClass().

提交回复
热议问题