2017-04-11 30 views
0

我使用下面的代碼添加一個類來鏈接到當前頁面:添加類使用jQuery當前頁面的鏈接僅適用於相對的而不是絕對鏈接

var pathname = window.location.pathname; 
$("ul#inventory-categories a").each(function() { 
    var href= $(this).attr("href"); 
    if (href.length && pathname.indexOf(href) >= 0){ 
     $(this).addClass("active"); 
    } 
}); 

也能正常工作相對鏈接,但不是絕對的聯繫。

任何人都可以提供任何見解嗎?

+0

你能不能給我們那些和不工作的例子嗎? –

+0

你可以添加示例鏈接嗎? – fubar

+0

當您處理絕對鏈接時,您正在檢查整個URL。那麼你的路徑名是否真的有'http://www.example.com'? – itamar

回答

1
​​

或...

var pathname = window.location.pathname; 
var url = window.location.href; 
$("ul#inventory-categories a").each(function() { 
    var href= $(this).attr("href"); 
    if (href.length && ((pathname.indexOf(href) >= 0) || ((url.indexOf(href) >= 0)){ 
     $(this).addClass("active"); 
    } 
}); 

(未測試)

+0

第一個做到了。謝謝! –

0

window.location.pathname只給你的路徑。也許你的意思是href.indexOf(pathname)

相關問題