我一直在尝试使脚本正常工作,但显然有问题:当我尝试使用浏览器后退按钮向后移动时,它在第一页后退时停止,即第二次单击后退按钮时不起作用正确地更新自己的当前页面。
示例:主页->第二页->第三页->第二页->第二页->第二页(依此类推)
主页->第二页->第三页->第四页->第三页->第三页(依此类推)
相反,它可以工作:主页->第二页->主页
有人知道我失踪了吗?
var domain = 'http://example.com/';
function updatePage(json){
var postData = JSON.parse(json);
// pushState
var url = domain + postData.url;
var title = postData.title;
document.title = title;
history.pushState({"page": url}, title, url);
// Clears some elements and fills them with the new content
// ...
// Creates an 'a' element that triggers AJAX for the next post
var a = document.createElement('a');
a.innerHTML = postData.next;
a.href = domain + postData.next;
document.getElementById('container').appendChild( a );
listenerAttacher( a );
// Creates another 'a' element that triggers AJAX for the previous post
a = document.createElement('a');
a.innerHTML = postData.previous;
a.href = domain + postData.previous;
document.getElementById('container').appendChild( a );
listenerAttacher( a );
}
function loadPost( resource ){
// Loads post data through AJAX using a custom function
loadHTML( resource, function(){
updatePage( this.responseText );
});
}
function listenerAttacher( element ){
// Adds a click listener to an element.
element.addEventListener('click', function(e){
e.preventDefault();
e.stopPropagation();
loadPost( this.href +'.json' );
return false;
},
false);
}
(function(){
history.replaceState({'page': window.location.href}, null, window.location.href);
// Adds the event listener to all elements that require it.
var titles = document.querySelectorAll('.post-title');
for (var i = 0; i < titles.length; i++){
listenerAttacher( titles[i] );
}
// Adds a popstate listener
window.addEventListener('popstate', function(e){
if ( e.state == null || e.state.page == domain ){
window.location = domain;
}
else {
loadPost( e.state.page + '.json' );
}
}, false);
})();
当您按下返回按钮时,popstate
将触发事件并loadPost
调用函数。但是,在中loadPost
,history.pushState
方法会再次被调用,这会将当前页面再次推送到历史记录堆栈中。这就解释了为什么第一个后退按钮起作用,然后却不起作用。
1)一个快速解决方案是检查当前状态是否与您要推送的状态匹配:
if (!history.state || history.state.page!=url)
history.pushState({ "page": url }, title, url);
2)事件更好,您可以向loadPost
和添加参数updatePage
以防止不必要的pushState
调用:
function updatePage(json, disablePushState) {
...
// disablePushState is true when back button is pressed
// undefined otherwise
if (!disablePushState)
history.pushState({ "page": url }, title, url);
...
}
function loadPost(resource, disablePushState) {
// Loads post data through AJAX using a custom function
loadHTML(resource, function (responseText) {
updatePage(responseText, disablePushState);
});
}
...
window.addEventListener('popstate', function (e) {
if (e.state == null || e.state.page == domain) {
window.location = domain;
}
else {
loadPost(e.state.page + '.json', true);
}
return true;
});
希望能有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句