简体   繁体   中英

Back navigation with pushstate and load in jQuery

I'm currently using jQuery to dynamically load content into a holder div and then updating the url with pushstate.

I have the following code so far (some excluded for example simplicity):

$("body").on("click", "a:not(.noclick)", function(){

    history.pushState({path: $(this).attr("href")}, "", $(this).attr("href"));

    $("#main").load($(this).attr("href"));

    return false
});

It works as expected and the url changes to what it should be on new content load but the back button is currently unfunctional, when back is pressed the url changes to the previous but nothing else happens.

I have pages built in a way that you can either use the site with jQuery to load content without headers or without any javascript and pages display from their urls so there's no issue in that part.

Is there a way I could use load on back navigation to load the last pushstate history? I'd prefer to not use hashing but not sure if it's possible without?

Facebook seems to do this with their navigation if that helps?

https://developer.mozilla.org/en-US/docs/DOM/window.onpopstate

This link will help you, if you don't wish to use pjax.

You need a popstate event handler.

But why not make this someone else's problem by using jquery-pjax .

Once you've included the pjax script, probably the following would be sufficient:

$(function() {
  $("a:not(.noclick)").pjax("#main", { fragment: "#main" });
});

This particular usage doesn't require any server processing to remove the non- #main content, but pjax also supports the partial content that you refer to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM