2014-02-07 576 views
1

我有一些动态菜单。一旦有人点击链接进入菜单,我想突出显示这个点击菜单。JQuery选择性选择

$("#my_menu > li").click(function(){ 
    var clickedId = $(this).attr('id'); 
    $("#" + clickedId).css("font-weight", "bold"); 
    $("#" + clickedId).css("background-color", "#E0E0E0"); 
    $('#navigation_submenu').show(); //this is not important 
}); 

但现在我必须恢复到其他菜单的初始状态。 请有人可以帮助我如何做到这一点? 感谢

+3

为什么不只是$(this).css()而不是添加id字符串 – Anton

回答

5

更好的方式来做到这一点是使用addClass()removeClass()这样:

  • 首先在你的CSS创建活动项目类:

    .active { 
        font-weight:bold; 
        background-color:#E0E0E0; 
    } 
    
  • 然后用jQuery :

    $("#my_menu > li").click(function(){ 
        //Remove previous active item 
        $("#my_menu > li").removeClass('active'); 
        //Add class on clicked element 
        $(this).addClass('active') 
    }); 
    

选中此Demo Fiddle

3

像这样的事情?

CSS

li.active 
{ 
    font-weight: bold; 
    background-color: #E0E0E0; 
} 

的JavaScript

$("#my_menu > li").on("click", function() 
{ 
    $("#my_menu > li").removeClass("active"); 
    $(this).addClass("active"); 
}); 
3

使用CSS类为 “主动” 来代替。

$('.active').removeClass('active'); 
$(this).addClass('active'); 

而你当然需要一个CSS类的规范,你的大胆和更多。

编辑:Oups,我太慢了。其他人给了你几乎相同的答案。