HTML
    | Change particular
  • color onclick and other
  • in the same
      to default color

前端 未结 6 469
青春惊慌失措
青春惊慌失措 2021-01-18 22:06

I want to have 5 lists such than when any of them is clicked, it turns to green and turn the other lists to black if any of them is green.

Here\'s m

6条回答
  •  星月不相逢
    2021-01-18 22:52

    The way you do it:

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

    with this CSS for selected item:

    li.selected {
        color: green;
    }
    

    Don't ever use css method for such things, this is very obtrusive approach which requires you to modify JS code when you want to change styling. If tomorrow you decide to add a background image to selected item, what will you have to do if you go with .css approach? You should use classes for this, in this case you write JS once and forget about this. Styles are for CSS, UI logic is for JS.

    Here is a demo:

    var $li = $('#menu li').click(function() {
        $li.removeClass('selected');
        $(this).addClass('selected');
    });
    li.selected {
        color: green;
    }
    
    
    

提交回复
热议问题