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

Need to click twice to go back in history (using pushState)

本文关键字:历史 返回 记录 pushState 使用 两次      更新时间:2023-09-26

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

$(".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);

我猜你是Pushing当前状态当你达到的状态,而不是你推前一个状态当你达到当前状态。这就是为什么当你第一次按下后退键时,你会弹出当前状态,而你需要弹出前一个状态并回到那里。

let boxes = Array.from(document.getElementsByClassName('box'));
function selectBox(id) {
  boxes.forEach(b => {
    b.classList.toggle('selected', b.id === id);
  });
}
boxes.forEach(b => {
  let id = b.id;
  b.addEventListener('click', e => {
    history.pushState({
      id
    }, `Selected: ${id}`, `./selected=${id}`)
    selectBox(id);
  });
});
window.addEventListener('popstate', e => {
  selectBox(e.state.id);
});
history.replaceState({
  id: null
}, 'Default state', './');
.boxes {
  display: flex;
}
.desc {
  width: 100%;
  display: flex;
  align-items: center;
  padding: 3rem 0;
  justify-content: center;
  font-weight: bold;
}
.box {
  --box-color: black;
  width: 50px;
  height: 50px;
  margin: 20px;
  box-sizing: border-box;
  display: block;
  border-radius: 2px;
  cursor: pointer;
  color: white;
  background-color: var(--box-color);
  border: 5px solid var(--box-color);
  font-size: 14px;
  font-family: sans-serif;
  font-weight: bold;
  text-align: center;
  line-height: 20px;
  transition: all 0.2s ease-out;
}
.box:hover {
  background-color: transparent;
  color: black;
}
.box.selected {
  transform: scale(1.2);
}
#box-1 {
  --box-color: red;
}
#box-2 {
  --box-color: green;
}
#box-3 {
  --box-color: blue;
}
#box-4 {
  --box-color: black;
}
<div class="boxes">
  <div class="box" id="box-1">one</div>
  <div class="box" id="box-2">two</div>
  <div class="box" id="box-3">three</div>
  <div class="box" id="box-4">four</div>
</div>
<div class="desc">
  Click to select Each box and u can navigate back using browser back button
</div>

查看此代码:https://codepen.io/AmalNandan/pen/VwmrQJM?editors=1100