开发者

jquery/javascript - parsing url to see if you're on a certain page

So say you have some navigation, and you don't/can't use server side code to choose which link is "current". How can you use the 开发者_开发知识库first part of the url (as in after the first slash but before any next slash) i.e. (example.com/dashboard/view/16) would return dashboard. Of course there's not always a second slash, it could be (example.com/dashboard). Also before a hash mark i.e. (example.com/dashboard#users) would return dashboard.

Is the best choice to just use location.href and try to write some functions to parse it? Or is there something already made/simpler?


You should be able to do something like this:

var page = window.location.pathname.split('/')[1];

alert(page);​


Could the pathname property of the location be of interest?

From w3schools

hash   Returns the anchor portion of a URL
host  Returns the hostname and port of a URL
hostname  Returns the hostname of a URL
href  Returns the entire URL
pathname  Returns the path name of a URL
port  Returns the port number the server uses for a URL
protocol  Returns the protocol of a URL
search  Returns the query portion of a URL


It's easy enough to parse it yourself.

window.location.pathname.slice(1).split('/')[0]

is what you are looking for.


$("a[pathname="+location.pathname+"]")

That jQuery collection will contain all of the links that link to the current page. You could narrow it down to certain elements with a more specific selector and then apply a style to it.

For example:

$("#navigation a[pathname="+location.pathname+"]").css('color', 'red');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜