How to detect URL changes with jQuery

前端 未结 5 1749
梦谈多话
梦谈多话 2020-12-03 13:31

How can jQuery detect changes to a url?

For example: If a user goes to a page site.com/faq/ nothing shows, but if he goes to site.com/faq/#open

相关标签:
5条回答
  • 2020-12-03 13:53

    If you have a url of site.com/faq/#open, then you can do

    var hash = window.location.hash
    

    to get hash = 'open'

    0 讨论(0)
  • 2020-12-03 13:58

    Try This

    $(window).on('hashchange', function(e){
     // Your Code goes here
    });
    

    Its working for me

    0 讨论(0)
  • 2020-12-03 14:00

    You can use the hashchange event.

    function hashchanged(){
      var hash = location.hash.replace( /^#/, '' );
     //your code
    }
    
    window.addEventListener("hashchange", hashchanged, false);
    

    or integrate a jquery hashchange plugin

    $(function(){
    
      // Bind the event.
      $(window).hashchange(hashchanged);
    
      // Trigger the event (useful on page load).
      hashchanged();
    
    });
    
    function hashchanged(){
     var hash = location.hash.replace( /^#/, '' );
     //your code
    }
    
    0 讨论(0)
  • 2020-12-03 14:08

    Try this:

    if (window.location.hash) {
        // Fragment exists, do something with it
        var fragment = window.location.hash;
    }
    

    Just for reference, the part of a url specified by the # is called a 'fragment'

    0 讨论(0)
  • 2020-12-03 14:16

    Simply look at window.location.hash on page load:

    $(document).ready(function() {
        if(window.location.hash === "open")
        {
            //Show something
        }
    });
    

    Or bind to the hashchange event of the window:

    $(document).ready(function() {
        $(window).hashchange(hashchanged);
    });
    
    function hashchanged()
    {
        //Show something
    }
    
    0 讨论(0)
提交回复
热议问题