【发布时间】:2014-07-07 12:18:36
【问题描述】:
我有一个包含一些选择字段的页面。 一旦用户更改了选择字段的值,就会使用所有选择字段的值作为状态对象创建一个新的历史对象:
$(".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 时,一个选择字段会相应更改。但是浏览器本身在历史记录中的位置保持不变(不能前进,仍然是相同数量的回溯历史条目)。
然后我再次单击后退按钮。这次状态对象与我单击的列表时间相同。不过,浏览器会在历史记录中向后移动一个条目。
第三次单击后退按钮时,下一个选择字段会更改,但浏览器会再次保持该状态,除非我第四次单击。
谁能解释我做错了什么?
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(例如返回)上,您正在调用“restoreState”,它循环字段,并可能调用 .change(),它再次执行 history.pushState。如果 popstate 事件被触发,我建议执行 replaceState。
标签: javascript jquery html browser-history html5-history