且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在JavaScript中哈希后检测URL是否已更改

更新时间:2022-10-30 18:10:34

在现代浏览器(IE8 +,FF3.6 +,Chrome)中,您只能听在窗口上的 hashchange 事件。



在某些旧版本中浏览器,您需要一个计时器来连续检查 location.hash 。如果您使用的是jQuery,则可以使用插件来实现。 p>

How can I check if a URL has changed in JavaScript? For example, websites like GitHub, which use AJAX, will append page information after a # symbol to create a unique URL without reloading the page. What is the best way to detect if this URL changes?

  • Is the onload event called again?
  • Is there an event handler for the URL?
  • Or must the URL be checked every second to detect a change?

In modern browsers (IE8+, FF3.6+, Chrome), you can just listen to the hashchange event on window.

In some old browsers, you need a timer that continually checks location.hash. If you're using jQuery, there is a plugin that does exactly that.