The operation of the URL hash

Source: Internet
Author: User

First, what is a hash? How do I get a hash?

A hash is a property of the HTML DOM location object, which is a string that stores the anchor portion of the URL (the part that begins with the # number). Hash changes will not cause the browser to re-refresh, the specific code to obtain the hash is as follows:

var hash = Window.location.hash;

It is important to note that Firefox will decode the strings obtained by Location.hash, and if so, use the following code:

var url = window.location.href; var index = url.indexof (' # '); var hash = Index = =-1? " : Url.slice (index); return Hash;

Second, listen to hash execution corresponding logic

JavaScript provides event Hashchange to listen for hash, which has two properties: Oldurl and Newurl. It should be noted that this event is only compatible with ie8+ 's IE browser, so we use a script to simulate the event and bind the event handler on the Window.onhashchange.

(function(window) {
// self-Executing anonymous function //if the browser natively supports the event, exitif("Onhashchange"inchWindow.document.body) {return; } varLocation =window.location, Oldurl=Location.href, Oldhash=Location.hash; //every 100ms detects if the Location.hash has changedSetInterval (function() { varNewurl =Location.href, Newhash=Location.hash; //If the hash has changed and the processing function is bound ... if(Newhash! = Oldhash &&typeofWindow.onhashchange = = = "function" ) { //Execute the handlerwindow.onhashchange ({type:"Hashchange", Oldurl:oldurl, newurl:newurl}); Oldurl=Newurl; Oldhash=Newhash; } }, 100);}) (window);

The operation of the URL hash

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.