Jquery - Take text from current URL
I need to change the style of each page dynamically based on the page the user is on.
To do this I plan on taking the URL of the page being visited, stripping out some bits and pieces, and apply then apply the rresult to the <body>
tag. This will then allow me to style based on the nam开发者_开发技巧e of the page.
The URL I have looks something like:
http://dan.manfredman.net/site/user/location/home.php
http://dan.manfredman.net/site/user/location/profile.php
http://dan.manfredman.net/site/user/location/users.php
I need only 'home', 'profile', 'users', how can I use JQuery to remove the .php from the file name and then apply the remaining 'home', 'profile', 'users' to the body tag based on the page there visiting?
You'd probably be better off doing this on the server side, by applying a different CSS file, depending on which page you are on.
Depending on the platform that you are developing for - PHP, Java, ASP.NET, etc - there will be different ways of acheiving this.
A server side approach will work whether javascript is enabled on the client or not.
EDIT: I see that you have php file extensions, so I guess that you're developing for PHP - RTFP, Bob!
$(document).ready(function() {
var pathname = window.location.pathname;
var pathname_no_php = pathname.replace(/\.php$/i, "");
// => http://dan.manfredman.net/site/user/location/users
var pathname_splitted = pathname_no_php.split("/")._reverse()[0]
// => 'users'
$("body").attr("id", pathname_splitted);
});
You don't need jQuery for that, just use plain javascript:
var url = document.location.href;
var name = url.substring(
url.lastIndexOf("/")+1
, url.lastIndexOf(".")
);
why don't have a div and change the class using the jquery, and the css will follow automatically. you can hide some portions using css if you don't want and show the others. Changing the whole page might cause user noticing that the menu appeared earlier and disappeared.
var pathname = document.location.pathname;
var name = pathname.substring(pathname.lastIndexOf("/")+1, pathname.lastIndexOf("."));
精彩评论