2012-05-15 26 views
2

我有下面的代碼應該添加一個積極的CSS類的菜單項,如果菜單項的URL ==當前網址:jQuery的主動類的菜單項根據當前的URL

$("#accordion a").each(function() 
{ 
    if (this.href.search(window.location.hostname) != -1) 
    { 
     $(this).addClass("active-sidebar-link"); 
    } 
}); 

但是這增加了類到所有菜單項。有小費嗎?如果你想用jQuery做這個

$("#accordion a").each(function() { 
    if (this.href == window.location.href) { 
     $(this).addClass("active-sidebar-link"); 
    } 
}); 
+0

'window.location.hostname'會返回你的頁面主機名,即'stackoverflow.com'。您應該使用'location.href'或'location.pathname'來獲得正確的匹配。 – kayen

回答

11

試試這個

$("#accordion a").addClass(function(){ 
    return this.href === window.location 
    ? "active-sidebar-link" 
    : "" ; 
}); 

然而,有一種更好的方法來樣式當前頁面的鏈接。這通常涉及給予body元素對應於您的鏈接類名:

<body class="home"> 
    <a class="home" href="foo.html">Home</a> 
    <a class="contact" href="bar.html">Contact</a> 
</body> 

在這種情況下,你會選擇活動鏈接樣式是這樣的:

body.home a.home, 
body.contact a.contact { 
    color: green; 
} 

這種方法不需要JavaScript設置初始樣式,這總是很好。

+0

這可以工作,但是如果URL有片段,它會中斷。例如'domain.com/folder /#top'。 –

+0

使用'pathname'而不是'href'應該有所幫助。 –

3
$('#accordion a[href="'+ window.location.hostname +'"]').addClass('active-sidebar-link'); 
0

使用過濾功能:

$("#accordion a") 
.filter(function(){ 
    return location.href.match($(this).attr("href")) 
}) 
.addClass("active-sidebar-link"); 

只返回過濾元素,在這種情況下將與當前的URL鏈接,並增加了類active-sidebar-link它。