2012-03-14 73 views
0

好吧,自動選擇當前類 - 導航菜單

所以我試圖做到的是具有與該「選擇」類標誌着頁當前最終用戶更新導航上。

我已經嘗試了很多東西。但是,似乎沒有任何工作。這裏是我的代碼:

jQuery的:

jQuery(function() { 
    var path = location.pathname.substring(1); 
    if (path) 
     jQuery('.navigation ul li a[href$="' + path + '"]').attr('class', 'selected'); 
}); 

的HTML:

<div class="navigation"> 
    <ul> 
     <li><a href="index.html">HOME</a></li> 
     <li><a href="team.html">TEAM</a></li> 
     <li><a href="about.html">ABOUT</a></li> 
     <li><a href="services.html">SERVICES</a></li> 
     <li><a href="portfolio.html">PORTFOLIO</a></li> 
     <li><a href="contact.html">CONTACT</a></li> 
    </ul> 
    <div class="clear"></div> 
</div> 

的CSS:

.navigation li a.selected { 
    background: url(../images/navigation-background-active.png) repeat-x; 
    text-decoration: none; 
} 

我f您對我所要求的內容感到困惑...您可以查看此鏈接: http://docs.jquery.com/Tutorials:Auto-Selecting_Navigation

非常感謝!

回答

1

編輯:我看着你的網站和路徑的值是portfolio/newish/index.html

也許你應該substring基於lastIndexOf/。嘗試下面,

jQuery(function() { 
    var path = location.pathname; //return /portfolio/newish/index.html 
    path = path.substring(path.lastIndexOf('/') + 1); //will return index.html 

    if (path) 
     jQuery('.navigation ul li a[href$="' + path + '"]').addClass('selected'); 
}); 

你的代碼看起來罰款,是的,但我認爲你應該使用.addClass添加一個類的元素。嘗試下面,

jQuery('.navigation ul li a[href$="' + path + '"]').addClass('selected'); 
+1

不知道這是否能解決您的問題,但您可能也可以將選擇器縮短爲''.navigation a [href $ =''+ path +'「]'' – 2012-03-14 19:19:38

+0

@MikeTangolics:Welp,解決了我的問題,但他們確實縮短了我的代碼。謝謝! – 2012-03-14 19:22:40

+0

@SKS:謝謝,雖然沒有解決。 – 2012-03-14 19:22:51

1

是否已確認location.pathname.substring(1)的輸出,你想到什麼?那就是,index.html等?

path function works(JS加show,因爲iframe的),你的選擇看起來是正確的,所以我能想到的唯一的事情是,你期待它輸出的路徑是不是有什麼是您的網站被輸出。