JavaScript function if url has hash tag and user h

2019-05-31 00:32发布

问题:

The following will fire an alert when the page is refreshed if the hash tag ends in twoB:

if (window.location.href.match(/\#twoB/))
{
   alert('twoB');
}

The issue is that if you've clicked on a few hash tags and then click back in your browser, although the URL includes the hash the alert doesn't fire. How can I make the code fires (ideally only) after a user has gone back or forward with their browser.

I'm using jQuery for this project so i would like a jQuery solution in an ideal world if the syntax is easier.

回答1:

$(window).on("hashchange", function () {
    console.log("hash is now " + window.location.hash);
});

Note that on was added in jQuery 1.7; if you're using an older version, then do $(window).bind instead.



回答2:

Initially I solved this quite an ugly way of using setInterval to repeatedly check the URL. HTML5s onpopstate runs when the page is first loaded and then every forward and back navigation aswell.

window.onpopstate = function(){ 
  if (window.location.href.match(/\#twoB/))
  {
     alert('twoB');
  }
}


回答3:

Why don't you use location.hash instead of href.match? The location.hash should be faster as you are only getting the hash and you don't have to do a match?