2012-05-12 50 views
0

UPDATE:的jQuery - 添加活動類導航鏈接建立與jQuery UI的手風琴

使用正則表達式的網址試圖和它的作品:

var url = window.location.pathname, 
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); 

$("#accordion a").each(function() 
{ 
    if(urlRegExp.test(this.href.replace(/\/$/,''))) 
    { 
     $(this).addClass("active-sidebar-link"); 
    } 
}); 

我使用jQuery UI的摺疊菜單爲我的網站構建一個側欄導航菜單。 http://jqueryui.com/demos/accordion/

我有以下代碼:

// create accordion 
$("#accordion").accordion(
{ 
    header: '> li, h3:not(> li > ul)', 
    collapsible: true, 
    autoHeight: false, 
    navigation:true 
}); 

// Add active class to active sidebar links 
$("#accordion a").each(function() 
{ 
    if (this.href == window.location || this.href == document.location.protocol + "//" + window.location.hostname + window.location.pathname) 
    { 
     $(this).addClass("active-sidebar-link"); 
    } 
}); 

手風琴作品和 「導航:真正的」 選項也可以(http://jqueryui.com/demos/accordion/#option-navigation) ,它會根據您訪問的鏈接打開合適的手風琴「抽屜」。

但是活動類沒有被添加到當前鏈接。

任何想法?

+0

我想你可能需要一個正則表達式。 href =「http://www.website.com」和href =「http://website.com/」之間的區別是什麼? – bozdoz

+0

嘗試與正則表達式仍然無法正常工作。添加了正則表達式代碼問題。 – IntricatePixels

回答

0

我會對href值做一個搜索功能。如果您有鏈接到多個頁面,那麼你可以採取進一步的代碼包括window.location.pathname,但這裏有上搜索域名一個良好的開端:

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

或者,正如我在我的評論說上面,你可以想要改用正則表達式。

+0

正則表達式是贏家謝謝!我用於這個網站的平臺很爛並且沒有更新,這就是爲什麼我說它第一次無法正常工作。回覆:搜索解決方案,這使得我的所有鏈接都處於活動狀態,所以在這種情況下沒什麼用處,但將其標記爲正確的答案。 – IntricatePixels