2016-08-12 59 views
0

我有jquery腳本,將clas添加到specfic李。第一個3 li 它添加類,但如果點擊4th到最後一個li不適用。請 幫我一下:如何添加類當活動菜單 - jquery

html: 

<ul class="sidebar-menu" id = "navigation"> 
    <li><a href="www.site.com/dashboard">Dashboard</a></li> 
    <li><a href="wwww.site.com/mycoupon">My Coupons</a></li> 
    <li><a href="www.site.com/member">View Profile</a></li> 
    <li><a href="www.site.com/update">Update Profile</a></li> 
</ul> 

Jquery: 

$(document).ready(function() { 
    var current_page = document.URL; 

    if (current_page.match(/dashboard/)){ 
     $("ul#navigation li:eq(0)").addClass('selected sel'); 
    } 

    else if (current_page.match(/mycoupon/)){ 
     $("ul#navigation li:eq(1)").addClass('selected sel'); 
    } 

    else if (current_page.match(/member/)){ 
     $("ul#navigation li:eq(2)").addClass('selected sel'); 
    } 

    else if (current_page.match(/update/)){ 
     $("ul#navigation li:eq(3)").addClass('selected sel'); 
    } 

    else { // don't mark any nav links as selected 
     $("ul#navigation li").removeClass('selected sel'); 
    } 
}); 
+0

這是爲我工作。 – James

+0

哦,在我的身邊有股票3只李嗚 – coolshox

回答

1

,而不是爲每個菜單編寫代碼,你可以簡單地使用這樣的,

$(document).ready(function() { 
    var current_page = document.URL; 
    $("#navigation li a").filter(function() { 
    return current_page.indexOf($(this).attr("href")) > -1 
    }).closest("li").addClass("selected sel"); 
}); 
+1

拯救你我的日子Anoop喬希非常感謝 – coolshox

+0

@coolshox你總是歡迎:) –

相關問題