How can you check for a #hash in a URL using JavaS

2018-12-31 05:00发布

I have some jQuery JavaScript code that I want to run only when there is a hash (#) anchor link in a URL. How can you check for this character using JavaScript? I need a simple catch-all test that would detect URLs like these:

  • example.com/page.html#anchor
  • example.com/page.html#anotheranchor

Basically something along the lines of:

if (thereIsAHashInTheUrl) {        
    do this;
} else {
    do this;
}

If anyone could point me in the right direction, that would be much appreciated.

18条回答
爱死公子算了
2楼-- · 2018-12-31 05:32
  if(window.location.hash) {
      var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
      alert (hash);
      // hash found
  } else {
      // No hash found
  }
查看更多
何处买醉
3楼-- · 2018-12-31 05:33
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
查看更多
冷夜・残月
4楼-- · 2018-12-31 05:37

Put the following:

<script type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
</script>
查看更多
春风洒进眼中
5楼-- · 2018-12-31 05:41

If the URI is not the document's location this snippet will do what you want.

var url = 'example.com/page.html#anchor',
    hash = url.split('#')[1];

if (hash) {
    alert(hash)
} else {
    // do something else
}
查看更多
萌妹纸的霸气范
6楼-- · 2018-12-31 05:42

Most people are aware of the URL properties in document.location. That's great if you're only interested in the current page. But the question was about being able to parse anchors on a page not the page itself.

What most people seem to miss is that those same URL properties are also available to anchor elements:

// To process anchors on click    
jQuery('a').click(function () {
   if (this.hash) {
      // Clicked anchor has a hash
   } else {
      // Clicked anchor does not have a hash
   }
});

// To process anchors without waiting for an event
jQuery('a').each(function () {
   if (this.hash) {
      // Current anchor has a hash
   } else {
      // Current anchor does not have a hash
   }
});
查看更多
永恒的永恒
7楼-- · 2018-12-31 05:44

This is a simple way to test this for the current page URL:

  function checkHash(){
      return (location.hash ? true : false);
  }
查看更多
登录 后发表回答