WindowEventHandlers.onhashchange - Web APIs 编辑

The WindowEventHandlers.onhashchange property of the WindowEventHandlers mixin is the EventHandler for processing hashchange events.

The hashchange event fires when a window's hash changes (see Window.location and HTMLHyperlinkElementUtils.hash).

Syntax

Using an event handler:

window.onhashchange = funcRef;

Using an HTML event handler:

<body onhashchange="funcRef();">

Using an event listener:

To add an event listener, use addEventListener():

window.addEventListener("hashchange", funcRef, false);

Parameters

funcRef
A reference to a function.

Examples

Using an event handler

This example uses an event handler (window.onhashchange) to check the new hash value whenever it changes. If it equals #cool-feature, the script logs a message to the console.

function locationHashChanged() {
  if (location.hash === '#cool-feature') {
    console.log("You're visiting a cool feature!");
  }
}

window.onhashchange = locationHashChanged;

Using an event listener

This example uses an event listener to log a notification whenever the hash has changed.

function hashHandler() {
  console.log('The hash has changed!');
}

window.addEventListener('hashchange', hashHandler, false);

Overriding the hash

This function sets a new hash dynamically, setting it randomly to one of two values.

function changeHash() {
  location.hash = (Math.random() > 0.5) ? 'location1' : 'location2';
}

The hashchange event

The dispatched hashchange event has the following properties:

FieldTypeDescription
newURLDOMStringThe new URL to which the window is navigating.
oldURLDOMStringThe previous URL from which the window was navigated.

Polyfill for event.newURL and event.oldURL

// Let this snippet run before your hashchange event binding code
if (!window.HashChangeEvent)(function(){
  var lastURL = document.URL;
  window.addEventListener("hashchange", function(event){
    Object.defineProperty(event, "oldURL", {enumerable:true,configurable:true,value:lastURL});
    Object.defineProperty(event, "newURL", {enumerable:true,configurable:true,value:document.URL});
    lastURL = document.URL;
  });
}());

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'onhashchange' in that specification.
Living Standard 
HTML 5.1
The definition of 'GlobalEventHandlers' in that specification.
Recommendation 
HTML5
The definition of 'GlobalEventHandlers' in that specification.
Recommendation 

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:66 次

字数:6557

最后编辑:8年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文