当popstate事件发生时,HTML5历史API返回错误的历史状态数据。以下是一些push和pop事件响应(已在控制台记录)。
JS
/*
* JS USED TO PUSH HISTORY
*/
var markers = [];
var markerIndexes = [];
// mapOverlays (array) is a global variable containing all marker and infowindow objects
var overlayIndex = mapOverlays.length;
var historyData = {
"historyDetails": {
"append": true,
"popState": false
},
"title": null,
"url": ""
};
for (var i = 1; i < data.length; i++) {
// this function creates a marker with infowindow and pushes marker & infowindow objects to mapOverlays array
addActionMarkerToGMap(data[i].lat, data[i].lng, 'Demo info window', false);
}
for (var i = overlayIndex; i < mapOverlays.length; ++i) {
markers.push(mapOverlays[i].marker);
markerIndexes.push(i);
}
historyData.historyDetails.markerIndexes = markerIndexes;
window.history.pushState(historyData.historyDetails, historyData.title, historyData.url);
/*
* POPSTATE EVENT HANDLER
*/
window.addEventListener('popstate', function (event) {
if (event.state != null && event.state != "" && typeof event.state == "object") {
var popstateData = {
historyDetails: {
append: event.state.append,
popState: true, // hard coded because this is result of popstate event
markerIndexes: event.state.markerIndexes
}
};
console.log(popstateData);
}
});
推送状态 1
以下 JSON 在第一次 AJAX 请求完成时被推送。
{
"historyDetails":{
"append":false,
"popState":false,
"markerIndexes":[
0,
1,
2
]
},
"title":null,
"url":""
}
推送状态2
当第二个AJAX请求完成时,该JSON对象将被推送到历史记录中。
{
"historyDetails":{
"append":true,
"popState":false,
"markerIndexes":[
3,
4,
5
]
},
"title":null,
"url":""
}
弹出状态1
当我点击浏览器后退按钮时,会返回Push状态1而不是Push状态2。这就是弹出状态事件的返回值。
{
"historyDetails":{
"append":false,
"popState":true,
"markerIndexes":[
0,
1,
2
]
},
"title":null,
"url":""
}
如上所示,历史API不会返回最近的PUSH STATE数据。非常感谢您的帮助。
谢谢。