gpt4 book ai didi

JavaScript onpopstate 替代品,具有与 onhashchange 相同的功能

转载 作者:行者123 更新时间:2023-11-28 01:46:41 24 4
gpt4 key购买 nike

我在 Google 上搜索过,并在这个论坛中搜索过一些其他问题,但似乎没有回答我的问题。

基于 MDN https://developer.mozilla.org/en-US/docs/Web/API/window.onpopstate :

Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a clicking on the back button (or calling history.back() in JavaScript). And the event is only triggered when the user navigates between two history entries for the same document.

我正在寻找与 window.onhashchange ( https://developer.mozilla.org/en-US/docs/Web/API/Window.onhashchange ) 功能相同的 onpopstate 替代方案,该替代方案将在 URL 更改时触发事件。

您愿意分享您的解决方案吗?

最佳答案

我认为您可能可以使用“History.js”工具,它提供了您可以监听的“statechange”事件。当按下前进/后退按钮或使用 PushState/replaceState 时,该工具会触发该事件。

https://github.com/browserstate/history.js/

当然,现在您遇到了一个不同的问题,即两种类型的操作都会触发事件,并且您经常想要区分它们,而这会更加困难。所以你必须破解自己的解决方案来区分它们。大多数人似乎在每次调用 PushState/replaceState 时都会设置一些全局标志,然后在事件处理程序中检查此标志。如果设置了该标志,则该事件来自您自己的代码,如果没有设置,则该事件来自浏览器按钮。

关于JavaScript onpopstate 替代品,具有与 onhashchange 相同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20210037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com