[removed] only effecting page range of one

2019-08-01 08:31发布

I have a function that loads dynamic content from a database, it is called when certain links are clicked on:

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>

I am wanting to enable pushState and onpopstate.

I can enable the URL and browser history change by uncommenting the above history.pushState line - navigating forwards and backwards across several pages works correctly.

But this does not load the content.

A while back I think I had full functionality (ie navigation and content loading) with the addition of these elements:

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

I therefore tried adding them to a separate block:

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

But this causes the page range when navigating to be limited to one, and I cannot navigate forwards.

How can I achieve both navigation and content loading using the above code as a basis?

Edit

And for reference, the correct paths are in the browser history, it's just they can't be navigated (FF and Chrome) and the corresponding content is not loading. No errors in Firebug.

1条回答
冷血范
2楼-- · 2019-08-01 09:24

I think this is the answer, I came across this:

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

"Also ensure that pages loaded in onpopstate() don't try and push use pushState() themselves".

So I kept this:

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

But removed this from the function:

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

And added it instead to the jQuery triggered on click eg:

$(document).on("click","#main_menu a", function (e) {
href = $(this).attr("href");
loadContent(href);
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
查看更多
登录 后发表回答