window.onpopstate仅影响一个页面范围
我有一个从数据库加载动态内容的函数,当点击某些链接时调用它:
jQuery的
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); }); };
我想启用pushState
和onpopstate
。
我可以通过取消注释上面的history.pushState
行来启用URL和浏览器历史记录更改 – 在多个页面中向前和向后导航可以正常工作。
但这不会加载内容。
前一阵子我认为我有完整的function(即导航和内容加载),并添加了以下元素:
window.onpopstate = function(event) { console.log("pathname: "+location.pathname); loadContent(location.pathname); };
因此我尝试将它们添加到一个单独的块中:
$(document).ready(function() { window.onpopstate = function(event) { console.log("pathname: "+location.pathname); loadContent(location.pathname); }; });
但这会导致导航时的页面范围限制为1,我无法向前导航。
如何使用上面的代码作为基础来实现导航和内容加载?
编辑
作为参考,正确的路径在浏览器历史记录中,只是它们无法导航(FF和Chrome)并且相应的内容未加载。 Firebug中没有错误。
我想这就是答案,我遇到了这个:
https://stackoverflow.com/a/10176315/1063287
“还要确保在onpopstate()中加载的页面不会尝试推送使用pushState()”。
所以我保留了这个:
但是从function中删除了这个:
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(); });