JavaScript function if url has hash tag and user h

2019-05-30 23:46发布

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.

3条回答
男人必须洒脱
2楼-- · 2019-05-31 00:32
$(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.

查看更多
贼婆χ
3楼-- · 2019-05-31 00:35

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');
  }
}
查看更多
叼着烟拽天下
4楼-- · 2019-05-31 00:40

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?

查看更多
登录 后发表回答