在初始浏览器窗口加载后,History.js不会触发

时间:2012-09-21 15:50:45

标签: javascript jquery history.js

    $(function(){

        // Prepare
        var History = window.History; // Note: We are using a capital H instead of a lower h
        if ( !History.enabled ) {
             // History.js is disabled for this browser.
             // This is because we can optionally choose to support HTML4 browsers or not.
            return false;
        }

        // Bind to StateChange Event
        History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
            var State = History.getState(); // Note: We are using History.getState() instead of event.state
            History.log(State.data, State.title, State.url);
        });
});

我正在尝试使用history.js作为跟踪状态更改(前进和后退按钮)的方法,并且似乎只有当我打开一个新的浏览器窗口并从那里开始工作时才会触发window.statechange。记录初始前进和后退事件,但后续事件不是。

为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

我意识到这个问题很老了。解决方案是将状态转换函数移动到body load函数之外:

// Bind to StateChange Event
History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
    var State = History.getState(); // Note: We are using History.getState() instead of event.state
    History.log(State.data, State.title, State.url);
});

$(function(){

    // Prepare
    var History = window.History; // Note: We are using a capital H instead of a lower h
    if ( !History.enabled ) {
         // History.js is disabled for this browser.
         // This is because we can optionally choose to support HTML4 browsers or not.
        return false;
    }

});