2011-02-09 65 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

相關問題