2014-01-10 57 views
0

我有我的菜單這裏:jQuery的匹配前綴window.location.pathname

<ul> 
    <li class="step-1"><a href="/why-build">Why Build</a></li> 
    <li class="step-2"><a href="/land">Land</a></li> 
    <li class="step-3"><a href="/builders">Builders</a></li> 
</ul> 

我嘗試添加「選擇」菜單項時,我該網頁(即/爲什麼建造)的類,或它的子頁面(即/ why-build/page1或/ why-build/page2等)。第一個李將是

<li class="step-1 selected"><a href="/why-build">Why Build</a></li> 

所以基本上所有的url匹配pattern/why-build/*。我如何檢查window.location.pathname?對不起,我不擅長正則表達式。乾杯。

回答

1

使用.filter()來匹配路徑名的開頭與href

$("li").removeClass("selected"); 
$("li > a").filter(function() { 
    return window.location.pathname.indexOf($(this).attr('href')) == 0; 
}).parent().addClass("selected"); 

這裏假設你沒有做一些愚蠢就像文件夾/why-build/why-build2。我可以讓它更安全,在路徑名中顯式搜索/,然後比較子字符串或使用正則表達式。如果你需要這個,請把它看作一個學習練習。

+0

但不要我們需要做相反?當我們在page/why-build/page2上時,window.location.pathname =/why-build/page2。然後/爲什麼構建不匹配[href^='/ why-build/page2'],'selected'類無法添加。 – Alex

+0

是的,我知道了。我用'.filter'重做了它。 – Barmar

+0

非常感謝。它效果很好。 – Alex

0

使用下列匹配

HTML

<ul> 
    <li class="step-1"><a href="/why-build">Why Build</a></li> 
    <li class="step-1"><a href="/why-build/page1">Why Build</a></li> 
    <li class="step-2"><a href="/land">Land</a></li> 
    <li class="step-3"><a href="/builders">Builders</a></li> 
</ul> 

腳本

$("li").removeClass("selected"); 
$("a[href*='why-build']").parent('li').addClass("selected"); 

以下是屬性選擇象徵符號:

= is exactly equal 
!= is not equal 
^= is starts with 
$= is ends with 
*= is contains 

這裏的工作演示:http://jsfiddle.net/MbGE2/

欲瞭解更多詳情,請參閱:jQuery selectors