Javascript 需要单击两次以返回历史记录(使用pushState)

Javascript 需要单击两次以返回历史记录(使用pushState),javascript,jquery,html,browser-history,html5-history,Javascript,Jquery,Html,Browser History,Html5 History,我有一个页面,上面有一些选择字段。 用户更改选择字段的值后,将使用所有选择字段的值作为状态对象创建新的历史对象: $(".chosen-select-field").chosen().change(function() { $(".chosen-select-field").each( function ( index ) { parameterNames[index].value = $( this ).val(); })

我有一个页面,上面有一些选择字段。 用户更改选择字段的值后,将使用所有选择字段的值作为状态对象创建新的历史对象:

$(".chosen-select-field").chosen().change(function() {
    $(".chosen-select-field").each( function ( index ) {
        parameterNames[index].value = $( this ).val();
    });
    history.pushState(parameterNames, '', newUrl);
});
parameterNames是包含键和值的对象数组,例如

parameterNames.push({key:"name", value:"foobar"});
以下代码将恢复用户单击浏览器中的“后退”或“前进”按钮时的状态。它可以工作,但行为出乎意料

例如,我更改了三个选择字段(创建三个历史记录条目)。然后我回去。执行restoreState时,一个选择字段将相应更改。但是浏览器本身在历史记录中保持相同的位置(无法前进,返回历史记录条目的数量仍然相同)

然后我再次点击后退按钮。这次state对象与我单击列表时交付的对象相同。但浏览器会在历史记录中向后移动一个条目

第三次单击“后退”按钮时,“下一个选择”字段将更改,但浏览器将再次保持该状态,除非我第四次单击

谁能解释我做错了什么

var restoreState = function(event) {
    event = event.originalEvent;
    parameterNames = event.state;
    $(".chosen-select-field").each( function ( index ) {
        if ($( this ).val() != parameterNames[index].value){
            $( this ).val(parameterNames[index].value).change();
            $( this ).trigger('chosen:updated');
        }
    });
};

// Bind history events
$(window).bind("popstate",restoreState);
在popstate上(例如,back),您正在调用“restoreState”,它循环字段,并可能调用.change(),它再次执行history.pushState。我建议在触发popstate事件时执行replaceState。