Javascript window.location.href 上的 onchange 事件

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

onchange event on window.location.href

javascriptjquery

提问by Puchacz

I would like to trigger some Javascript function when window.location.hreflink changes. Is it possible?

我想在window.location.href链接更改时触发一些 Javascript 功能。是否可以?

Something like this:

像这样的东西:

$(window.location.href).on('change', function(){
   doSomething();
});

回答by elzi

You said 'something like', given the example code you're probably looking for the onbeforeunloadevent handler.

您说的是“类似”,给出了您可能正在寻找onbeforeunload事件处理程序的示例代码。

From the Mozilla docs:

来自Mozilla 文档

window.onbeforeunload = function(e) {
  return 'Dialog text here.';
};

回答by ashwin1014

The hashchange event occurs when there has been changes to the URL anchor part i.e after the #

当 URL 锚部分发生更改时,即在 #

window.addEventListener('hashchange', function() {

    alert("Hash Changed");

});