window.onpopstate只影响一的页面范围



我有一个从数据库加载动态内容的函数,当点击某些链接时会调用它:

jQuery

<script>
function loadContent(href){
$.getJSON("/route", {cid: href, format: 'json'}, function(results){  
$("#content_area").html("");
$("#content_area").append(results.content);
reinitFunc1();
reinitFunc2();
reinitFunc3();
// history.pushState('', 'New URL: '+href, href);
});
};
</script>

我想要启用pushStateonpopstate

我可以通过取消注释上面的history.pushState行来启用URL和浏览器历史记录更改——在几个页面上前后导航可以正常工作。

但这不会加载内容。

不久前,我认为添加了以下元素后,我拥有了完整的功能(即导航和内容加载):

window.onpopstate = function(event) {
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};

因此,我尝试将它们添加到一个单独的块中:

<script>
$(document).ready(function() {
window.onpopstate = function(event) {
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
</script>

但这导致导航时的页面范围被限制为一个,并且我无法向前导航。

如何使用以上代码实现导航和内容加载?

编辑

作为参考,正确的路径在浏览器历史记录中,只是它们无法导航(FF和Chrome),相应的内容也没有加载。Firebug中没有错误。

我想这就是答案,我遇到了这个:

https://stackoverflow.com/a/10176315/1063287

"还要确保onopstate()中加载的页面不会试图推送使用pushState()本身"。

所以我保留了这个:

<script>
$(document).ready(function() {
window.onpopstate = function(event) {
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
</script>

但将其从功能中删除:

history.pushState('', 'New URL: '+href, href);

并将其添加到点击时触发的jQuery中,例如:

$(document).on("click","#main_menu a", function (e) {
href = $(this).attr("href");
loadContent(href);
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});

最新更新