gpt4 book ai didi

javascript - 需要点击两次才能回到历史(使用pushState)

转载 作者:行者123 更新时间:2023-12-04 11:07:13 24 4
gpt4 key购买 nike

我有一个包含一些选择字段的页面。
一旦用户更改了选择字段的值,就会使用所有选择字段的值作为状态对象创建一个新的历史对象:

$(".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 事件被触发并且您循环选择字段时,如果条件 $( this ).val() != parameterNames[index].value满足时,当前的选择值将被改变,但也会触发 change 事件,这反过来又会再次调用将新状态插入历史的函数。这样,如果您回到历史,您将获得相同的状态对象。
因此,解决方案是检查是否触发了 popstate 事件,如果是,请不要调用 history.pushState ,但是,history.replaceState .

function handleHistoryStates(popstateEventWasFired = false) {
$(".chosen-select-field").each( function ( index ) {
parameterNames[index].value = $( this ).val();
});

if (popstateEventWasFired) {
history.replaceState(parameterNames, '', newUrl);
} else {
history.pushState(parameterNames, '', newUrl);
}
}

$(".chosen-select-field").chosen().change(handleHistoryStates);


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);
handleHistoryStates(true);
$( this ).trigger('chosen:updated');
}
});
};

// Bind history events
$(window).bind("popstate",restoreState);

关于javascript - 需要点击两次才能回到历史(使用pushState),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23739433/

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