1

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

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

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

但这不会加载内容。

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

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 中没有错误。

4

1 回答 1

0

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

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

“还要确保在 onpopstate() 中加载的页面不要尝试自己推送使用 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();
});
于 2013-11-22T11:32:48.750 回答