jquery - How to highlight a menu link when clicked?

前端 未结 4 974
春和景丽
春和景丽 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:20

    You should refer to the current element and not all elements matching your selector.

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

    I´d also recommend you to use CSS classes instead of setting the CSS properties this way.

    That would be something like;

    $("#mainMenu td").click(function() {
        $(this).addClass('selected');
    });
    

    together with;

    #mainMenu td.selected {
      background-color: #EDEDED;
    }
    

    EDIT

    The psuedo selector :visited should only be used on links (a) and you should not use tables more than you really need to.

    Created a jsFiddle that uses an ul list instead of the table and display: block on links to fill the entire parent li element.

    I´m also using event.preventDefault() to not follow the link as this probably would reload the page and not include the class for the selected/active link. If you want to follow the link and have the page reload you should use server side code to render that HTML.

    $("#mainMenu a").click(function(e) {
        e.preventDefault(); // Don´t follow the link
        $("#mainMenu a").removeClass('selected'); // Remove class on all menu items
        $(this).addClass('selected'); // Add class to current menu item
    });
    

提交回复
热议问题