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