What does this javascript code do? [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
开发者_如何转开发 Improve this questionthis code takes a url as input, but I'm not sure what it does or what's the benefit of doing this
var hashPos = url.lastIndexOf ( '#' );
return url.substring( hashPos + 1 );
It fetches the hash value off a URL:
So, if the URL is this: http://something.com/foo#xyz
, it gets the xyz
If there is no hash mark in the URL, this code returns the entire URL (which may not be the desired outcome).
This is probably a safer variation that returns an empty string, when there is no hash value:
var hashPos = url.lastIndexOf ( '#' );
if (hashPos != -1) {
return url.substring( hashPos + 1 );
} else {
return("");
}
It returns whatever is after the #
in the url.
Details:
var hashPos = url.lastIndexOf ( '#' ); // Gets the position of the last # found in the string.
return url.substring( hashPos + 1 ); // Gets a piece of the string starting at the given position (hashpos + 1).
It gets everything in the URL after the hash (#) mark.
var url = "http://www.mysite.com/test#somesection";
var hashPos = url.lastIndexOf ( '#' );
return url.substring( hashPos + 1 ); //returns "somesection"
Returns the part of the string from just after the last # character to the end. i.e a location in that page.
var hashPos = url.lastIndexOf ( '#' );
This grabs the location of the hash char (#) in the URL string.
return url.substring( hashPos + 1 );
This then returns everything after the location of the hash in the url string.
A result would be the hash tag. This is used alot for AJAX applications, where you would like to keep a page state, and be able to link to that state without actually linking to a seperate page.
An example would be:
var recent_hash = "";
setInterval(poll_hash, 100); // Initialize our hash polling interval for ajax urls
function poll_hash() {
if (url.substring( hashPos + 1 ) == recent_hash) { return; } // No change
recent_hash = url.substring( hashPos + 1 );
process_hash(recent_hash);
}
function process_hash(hash_id)
{
var ajax_url = '/ajax/link_hash/' + hash_id;
$('#some_div').load(ajax_url)
}
精彩评论