2011-02-09 35 views
1

对于我的网站的导航,我想给所有当前页面的链接一个颜色。
如何找到哪些链接指向当前页面?
链接的href就像“../index.php”,但当前页面是http://mysite.myserver.com/index.php链接指向此页面吗?

这是我目前的做法,不希望工作:

String.prototype.endsWith = function(str) { return (this.match(str + "$") == str); } 
String.prototype.startsWith = function(str) { return (this.match("^" + str) == str) } 
String.prototype.trim = function(sec) 
{ 
    var res = this; 

    while (res.startWith(sec)) 
    { 
     res = res.substr(sec.length); 
    } 

    while (res.endsWith(sec)) 
    { 
     res = res.substr(0, res.length - sec.length); 
    } 

    return res; 
} 

而且,当文档准备好:

$("a").each(
    function (i) 
    { 
     if (window.location.pathname.endsWith($(this).attr("href").trim("."))) 
     { 
      $(this).addClass("thispage"); 
     } 
    } 
); 

是的,我知道这可能颜色的家链接(../index.php - 因为所有页面都以此结束!)。这就是为什么我需要更好的方式...

回答

2
$("a[href]").filter(function() { 
    return window.location.pathname === this.pathname; 
}).addClass("thispage"); 

关于你的评论,如果window.location的是一个目录,你可以创建与index.php结尾的字符串。

var win = window.location.pathname; 
if(win.slice(-1) === '/') { 
    win += 'index.php'; 
} 
$("a[href]").filter(function() { 
    return win === this.pathname; 
}).addClass("thispage"); 
1

这是否必须在JavaScript中完成?看起来在您的页面生成代码中设置类会更容易。

+0

我将有很多页面,并且,我可能会在未来对标题进行更改。在复制和粘贴HTML时手动更改所有标签是一种痛苦,对吧? – Vercas 2011-02-09 19:09:38

+0

不应该,如果你提前计划。而且你不应该复制和粘贴太多。您应该改用由您选择的模板引擎提供的html生成和组合机制。 – ykaganovich 2011-02-09 20:31:26

+0

模板引擎?那是什么? – Vercas 2011-02-09 20:32:37

相关问题