For my website's navigation I want to give all the links to the current page a color.
How do I find which links are pointing to the current page? A link'shref
is like "../index.php" but the current page is http://mysite.myserver.com/index.php.
This is my current approach, which doesn't want to work:
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.l开发者_运维百科ength - sec.length);
}
return res;
}
And, when the document is ready:
$("a").each(
function (i)
{
if (window.location.pathname.endsWith($(this).attr("href").trim(".")))
{
$(this).addClass("thispage");
}
}
);
And yes, I know this might color the home link (../index.php - because all pages end with that!). That's why I need a better way...
$("a[href]").filter(function() {
return window.location.pathname === this.pathname;
}).addClass("thispage");
Regarding your comment, if the window.location is a directory, you can create a string that ends with index.php
.
var win = window.location.pathname;
if( win.slice(-1) === '/' ) {
win += 'index.php';
}
$("a[href]").filter(function() {
return win === this.pathname;
}).addClass("thispage");
Does this have to be done in javascript? It seems it would be easier to set the class in your page generation code.
Try the a:visited class. This allows you to specify the color of a visited tag. http://www.w3.org/TR/CSS2/selector.html#link-pseudo-classes
精彩评论