How can you check for a #hash in a URL using JavaScript?

前端 未结 19 3076
说谎
说谎 2020-11-22 02:10

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?

19条回答
  •  自闭症患者
    2020-11-22 02:31

    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
       }
    });
    

提交回复
热议问题