Javascript 如何使用 jQuery 检测 URL 更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8212845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:09:24  来源:igfitidea点击:

How to detect URL changes with jQuery

javascriptjqueryurl

提问by skywind

How can jQuery detect changes to a url?

jQuery 如何检测对 url 的更改?

For example: If a user goes to a page site.com/faq/nothing shows, but if he goes to site.com/faq/#openjquery detects it and does something.

例如:如果用户进入一个页面site.com/faq/什么都没有显示,但是如果他进入site.com/faq/#openjquery 会检测到它并做一些事情。

回答by user3354817

Try This

尝试这个

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

Its working for me

它为我工作

回答by UnLoCo

You can use the hashchangeevent.

您可以使用hashchange事件。

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

window.addEventListener("hashchange", hashchanged, false);

or integrate a jquery hashchange plugin

或者集成一个jquery hashchange 插件

$(function(){

  // Bind the event.
  $(window).hashchange(hashchanged);

  // Trigger the event (useful on page load).
  hashchanged();

});

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

回答by James Hill

Simply look at window.location.hashon page load:

只需查看window.location.hash页面加载:

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

Or bind to the hashchangeevent of the window:

或者绑定到hashchange窗口的事件:

$(document).ready(function() {
    $(window).hashchange(hashchanged);
});

function hashchanged()
{
    //Show something
}

回答by Rory McCrossan

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'

仅供参考,由 指定的 url 部分#称为“片段”

回答by Utku Y?ld?r?m

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

如果你有一个 url site.com/faq/#open,那么你可以做

var hash = window.location.hash

to get hash = 'open'

要得到 hash = 'open'