Javascript 如何在 jQuery 中触发 URL 更改?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12349907/
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-23 07:47:07  来源:igfitidea点击:

How can I trigger on URL change in jQuery?

javascriptjquery

提问by TGeorge

How can I trigger a function when the URL changes? I try something like:

URL更改时如何触发功能?我尝试类似:

$(windows.location).change(function(){
   //execute code
});

So my URL is something like http://www.mysite.com/index.html#/page/1. How can I execute jQuery or JavaScript code when the URL becomes something like http://www.mysite.com/index.html#/page/2?

所以我的 URL 类似于http://www.mysite.com/index.html#/page/1. 当 URL 变成类似 时,我如何执行 jQuery 或 JavaScript 代码http://www.mysite.com/index.html#/page/2

回答by David says reinstate Monica

That would be a hashchangeevent, so I'd suggest:

那将是一个hashchange事件,所以我建议:

$(window).on('hashchange', function(e){
    // do something...
});

JS Fiddle demo.

JS小提琴演示

References:

参考:

回答by techfoobar

Try the hashchangeevent, which is built exactly for this - http://benalman.com/projects/jquery-hashchange-plugin/

试试这个hashchange事件,它正是为此而构建的 - http://benalman.com/projects/jquery-hashchange-plugin/

回答by boz

You could also try using http://www.asual.com/jquery/address/

您也可以尝试使用http://www.asual.com/jquery/address/

$(function(){
    $.address.strict(false);

    $.address.internalChange(function(e) {
        // do something here
    });
});