popstate事件处理程序似乎无法正常工作 [英] popstate event handler seems not to work

查看:477
本文介绍了popstate事件处理程序似乎无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到'popstate'事件处理程序的问题,这是我的代码:

I'm having a problem with a 'popstate' event handler, this is my code:

window.addEventListener("popstate", function (event){
    if (event.state) {
        alert('abc')
    }
});

// The data object is arbitrary and is passed with the popstate event.
var dataObject = {
    createdAt: '2011-10-10',
    author: 'donnamoss'
};

var url = '/posts/new-url';
history.pushState(dataObject, document.title, url);

我预计这段代码会在执行时弹出警告框,但没有任何反应。

I expected this code will pop up an alert box when it's executed but, nothing happens.

这里有什么问题吗?

谢谢。

推荐答案

pushState 不要触发 popstate 事件,只需点击后退/前进按钮(或使用退格键)或调用 history.back() / history.go(n)将触发此事件。

pushState do not trigger the popstate event, only clicking back / forward button (or use backspace) or invoking history.back() / history.go(n) would trigger this event.

此外,在webkit浏览器中,页面的<$ c $后会触发 popstate 事件c> onload 事件,但Firefox和IE没有这种行为。

Also, in webkit browsers, a popstate event would be triggered after page's onload event, but Firefox and IE do not have this behavior.

这篇关于popstate事件处理程序似乎无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆