gpt4 book ai didi

javascript - HTML5 History API 初始加载问题

转载 作者:行者123 更新时间:2023-11-30 17:20:55 24 4
gpt4 key购买 nike

我试图在页面首次加载时存储第一页信息。以便我在点击第二页的时候能够取回第一页的信息。

(初始页 -> Page2 -> 初始页)

经过几个小时的工作,我决定存储一个名为 firstLoad 的全局变量,并使用 replaceState 代替 pushState。现在可以了。但是有一个问题,它不能这样走:

Initial Page -> Page2 -> Page3 -> Page2

Page 3回到Page 2时,控制台显示:

GET http://localhost/[object%20Object] 404 (Not Found) 

我用 Google 搜索过,但我找不到任何合适的教程来处理这个问题,他们中的大多数人建议使用 history.js,但我想先了解它是如何工作的。任何帮助将不胜感激!

<script>
$(function(){
var firstLoad = 1;

$('a').on('click', function(e){
e.preventDefault();
var path = this.href;
var currentPath = window.location.pathname;
loadContent(path);

if(firstLoad==1){
console.log(firstLoad);
console.log(currentPath);
firstLoad=0;
history.replaceState(currentPath, '', '');
history.pushState({},'',path);
}else{
console.log('Not first load')
history.pushState(path,'',path);
}
});

//Pop State
$(window).on('popstate', function(e){
var state = e.originalEvent.state;
if(e.originalEvent && state){
loadContent(state);
}
});

//Load Content
function loadContent(path){
$.get(path, function(data){
$('#result').html(data);
});
};

});
</script>

最佳答案

问题出在这段代码中。

$(window).on('popstate', function(e){
var state = e.originalEvent.state;
if(e.originalEvent && state){
loadContent(state);
}
});

如果我们检查 MDN page on Window.onpopstate我们发现 state 事件属性是传递给 pushState 等函数的状态对象。

the popstate event's state property contains a copy of the history entry's state object.

意思是jQuery事件对象属性e.originalEvent.state就是你在pushState上传入的对象。您可以使用此对象来存储数据,但您的 loadContent 函数需要 URL 的字符串,而不是对象。

我认为您实际上想在您的 popstate 处理程序中使用 document.location

$(window).on('popstate', function(e){
loadContent(document.location);
});

关于javascript - HTML5 History API 初始加载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25150661/

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