Ajax and back button. Hash changes, but where is previous page state stored?

前端 未结 2 1933
梦毁少年i
梦毁少年i 2021-02-07 22:43

I am trying to make ajax work with the back button and am missing something central. Where are the previous page states stored?

CASE 1:

Click \"make me re

2条回答
  •  爱一瞬间的悲伤
    2021-02-07 23:20

    Rather than using your JavaScript to drive your URLs, let your URLs drive your JavaScript. Let the window.onhashchange event handler do all the work. Everything else should just change the hash.

    You don't even need click handlers for links, just set the url to the right hash:

    Red
    

    Then, your hashchange handler takes care of the rest:

    function hashChange() {
        var page = location.hash.slice(1);
        if (page) {
            $('#content').load(page+".html #sub-content");
            document.title = originalTitle + ' – ' + page;
            switch (page) {
                // page specific functionality goes here
                case "red":
                case "yellow":
                    $("body").removeClass("red yellow").addClass(page);
                    break;
            }
        }
    }
    

    The only reason to change the hash at all is if you want to be able to come back to the page and have it load the same state based on the URL. So, you already have the requirement to let the URL drive the JavaScript, right? Else why are you changing the hash? Moving functionality out of click handlers, and into the hashchange event only simplifies things.

提交回复
热议问题