popState通过一次向后单击延迟

时间:2017-07-14 13:39:58

标签: javascript pushstate

要么我想念popstate,要么我发疯,无法弄清楚这里发生了什么。我正在使用firefox,每次我导航一点,然后尝试单击后退按钮我得到零状态但是当我再次点击它然后我得到状态?似乎有些事情被推迟了。一定是做错了。需要一些帮助。

$(document).ready(function(){

function makeid() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < 5; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
}


/* Global Variables */

var routes = [];

/* Recursivly Load Ajax */

function load_state(process_states){
    var state = process_states.shift();
    if (typeof(state) !== 'undefined'){
        jQuery.ajax({
            url: state.source,
            success: function(html) {
                $(state.target).empty().append(html);

                // Next itteration
                load_state(process_states);
            },
            async:false,
            cache:false,
        });

    }
}

/* Load page from URL */

function load_url(route, states, name){

    // Register route
    routes.push({'route': route, 'states': states, 'name': name});

    // Read current url
    var url = window.location.pathname;

    // Test url matches route
    if (route.test(url)){

        // Process matched route
        var process_states = states.slice();
        load_state(process_states);

        // Record state change
        history.pushState({'states': states}, makeid(), url);
    }
}

/* Pop State Event  */

$(window).on('popstate', function(evt){
    if (evt.state) {

        // Process route
        var states = evt.originalEvent.state.states;
        var process_states = states.slice();
        load_state(process_states);
    }
});

/* Click Link Envent */

$(document).on('click', '[data-name]', function(evt){
    evt.preventDefault();

    // Locate state with name
    var name = $(this).attr('data-name');
    var states_found = $.grep(routes, function(evt){ return evt.name === name; });

    // If state found load state
    if (states_found.length !== 0){
        var states = states_found[0].states;
        var process_states = states.slice();
        load_state(process_states);

        // Record state change
        history.pushState({'states': states.states}, 'ajax',name);
    }
});

/* Routing Table */

load_url(/^\/$/i, [
    {'target': '.body-ajax', 'source': '/ajax/public/'},
    {'target': '.page-ajax', 'source': '/ajax/public/home/'},
], '/');

load_url(/^\/two\/$/i, [
    {'target': '.body-ajax', 'source': '/ajax/public/'},
    {'target': '.page-ajax', 'source': '/ajax/public/two/'},
], '/two/');

load_url(/^\/contact\/$/i, [
    {'target': '.body-ajax', 'source': '/ajax/public/'},
    {'target': '.page-ajax', 'source': '/ajax/public/contact/'},
], '/contact/');

});

0 个答案:

没有答案