2017-04-11 34 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)

相关问题