javascript - window.onhashchange 是否会在单页应用程序上检测除导航以外的任何内容?

标签 javascript

我查看了有关检测单页应用程序导航的 stackoverflow 帖子,并且有多种解决方案。其中之一是使用 window.onhashchange 检测路径更改(基于哈希的路径)。

我的问题是:

window.onhashchange 是否用于检测路径更改(基于哈希的路径)以外的任何其他用途?

最佳答案

它是如何工作的?

window.onhashchange函数用于处理 hashchange事件。来自 the MDN docs :

The hashchange event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).

所以window.onhashchange函数就是用来检测片段标识符何时发生变化的,仅此而已。

为什么/什么时候应该使用它?

您使用 window.onhashchange 来检测片段标识符何时更改,因此“我应该何时使用 window.onhashchange?”问题与“我什么时候应该使用片段标识符?”有关。片段标识符的主要用途是引用(链接)到页面的特定部分,或者如何Wikipedia说:

In computer hypertext, a fragment identifier is a string of characters that refers to a resource that is subordinate to another, primary resource. The primary resource is identified by a Uniform Resource Identifier (URI), and the fragment identifier points to the subordinate resource.

The fragment identifier introduced by a hash mark # is the optional last part of a URL for a document. It is typically used to identify a portion of that document. ...

它还用于促进单页应用程序中的导航,以及出于各种其他原因(存储状态等)。您可以在 Wikipedia 上找到非常全面的片段标识符用法列表。 .

关于javascript - window.onhashchange 是否会在单页应用程序上检测除导航以外的任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959871/

相关文章:

javascript - 在线源代码编辑元素

javascript - 使用监听器更改的值执行 onevent

javascript - 根据数组返回 DOM 元素

javascript - React - 如何在推送到数组时添加 "key"

javascript - 覆盖 Javascript 函数中的回调

javascript - Angular $q 返回 promise 两次 $http 服务调用

javascript - 为什么我的数组的总和没有在点击事件中返回?

javascript - 在脚本加载时运行 javascript 函数

javascript - 如何使用纬度和经度获取位置名称或城市?

javascript - dojo 网格在 div 内不起作用