gpt4 book ai didi

javascript - History.js window.onstatechange 不触发

转载 作者:行者123 更新时间:2023-12-04 00:44:22 24 4
gpt4 key购买 nike

我只是一个js初学者,所以可能我只是理解不正确。但是,当您之前使用 History.stateObj 更改状态时,当您点击浏览器的后退/前进按钮时,window.onstatechange 不应该触发吗?

我实际上看到对象在 Firebug 控制台中发生变化,但是 window.onstatechange 就是不会触发!此外 - 非常令人困惑 - 当我改用 window.onpopstate 时,对象不再改变(使用后退/前进按钮时)。

这是我的做法:

$('.container').click(function(e) {
e.preventDefault();
var title = $(this).data('title');
stateObj = { show: title }
History.pushState(stateObj, document.title, '?show=' + title);
}

window.onstatechange = function() {
var title = History.getState().data['show'];
alert('title');
}

我已经从here找到了, 我必须使用

History.Adapter.bind(window,'statechange',function(){
var title = History.getState().data['show'];
alert('title');

});

...这有效,但我仍然不太明白为什么 window.onstatechange 不会触发?!

//编辑:Opened a ticket on Github

有什么建议吗?

最佳答案

Lucian Poston 于 2012 年 4 月在 GitHub 上回答了这个问题:

This seems to be the design of the History.Adapter event model. Have a look at the adapters' implementations e.g. https://github.com/balupton/history.js/blob/master/scripts/uncompressed/history.adapter.native.js

When history.js raises a 'statechange' event, it invokes History.Adapter.trigger(), which iterates over a list of event handlers setup via prior calls to History.Adapter.bind(). window.onstatechange() is not invoked as you expected.

Actually, History.Adapter.bind(window, 'statechange', function(){ alert('oi'); }) sets up window.onstatechange so that if fired, it would invoke History.Adapter.trigger(window, 'statechange'), which in turn would invoke the event handler, function(){ alert('oi'); }. If you redefine window.onstatechange as in your example, it would break that behavior.

关于javascript - History.js window.onstatechange 不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8503130/

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