jquery - How to highlight a menu link when clicked?

前端 未结 4 935
春和景丽
春和景丽 2021-01-27 17:51

I have a menu with links. The links are placed inside a table. Each link is placed in a . I want to change the background color of the

4条回答
  •  星月不相逢
    2021-01-27 18:17

    Your current code is

    $(function() {
        $("#mainMenu td").click(function() {
            $("#mainMenu td").css('background-color', '#EDEDED');
        });
    
    });
    ​
    

    That will change all tds in the table. Instead use $(this) inside your function to select the element that triggered the click event.

    $(function() {
        $("#mainMenu td").click(function() {
            $(this).css('background-color', '#EDEDED');
        });
    
    });
    ​
    

    To make the other ones revert back, use the siblings() selector to select all tds except the clicked one.

    $(function() {
        $("#mainMenu td").click(function() {
            $(this).css('background-color', '#EDEDED')
            .siblings().css('background-color', '#FFFFFF');
        });
    });
    

提交回复
热议问题