window.onhashchange是否可以检测单页应用程序上的导航以外的其他内容?

时间:2019-03-02 15:03:19

标签: javascript

我查看了关于在单页应用程序上检测导航的stackoverflow帖子,并且有各种解决方案。其中之一是使用<!DOCTYPE html> <html> <head> <title> User List </title> <link rel="stylesheet" href="/stylesheets/style.css" /> </head> <body> <h1> User List </h1> <ul> <% var list = ''; for (i = 0; i < userlist.length; i++) { list += '<li><a href="mailto:' + userlist[i].email + '">' + userlist[i].username + '</a></li>'; } return list; %> </ul> </body> </html>检测路径更改(基于哈希的路径)。

我的问题是这个

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

1 个答案:

答案 0 :(得分:1)

How does it works?

The window.onhashchange function is used for handling hashchange events. From 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).

So the window.onhashchange function is used to detect when the fragment identifier changes, nothing more, nothing less.

Why/When should you use it?

You use window.onhashchange to detect when the fragment identifier changes, so the "When should I use window.onhashchange?" question is related to "When should I use fragment identifier?". The main usage of fragment identifier is to refer (link) to a specific part of a page, or how Wikipedia puts it:

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. ...

It is also used to facilitate navigation in single page applications, and for various others reasons (storing state etc..). You can find quite comprehensive list of fragment identifier usages on Wikipedia.