简体   繁体   中英

Use Javascript history.go() to the real “previous” page

Assuming we have a history like this:

 - Home
 - Page 1
 - Page 2

JS history.go(-1) works well to go to Page 1... but what if our current history is

 - Home
 - Page 1
 - Page 2
 - Page 2 (2nd time)
 - Page 2 (3rd time)
 - ...
 - Page 2 (nth time)

How can we use JavaScript history object to go back to Page 1 ?

You could create a function that would do a +1 to a property of an object, you could then use this value to go back the right amount of steps

var History = {

    steps : 0

}

somenewpagelink.onclick = function() {

    History.steps = (parseInt(History.steps)+1);

}

Then if you want to go back to page 1, simple create another function:

function goBack() {

    History.go(-History.steps);
    History.steps = 0;

}

When you go back the steps will be reset so when you browse further in your site, it won't go back to many steps.

I do think using jQuery is a good solution but not for small things that can easily be solved with raw Javascript, it will only slow your site down if using jQuery for 1 function.

Furthermore you could add a switch in there that if when you click back to actually go back from page 3 to page 1, you could make it reverse too.

function goBack(r) {

    if (r)
        history.go(History.steps);
    else 
        history.go(-History.steps);
        History.steps = 0;

}

Ofcourse this function would require the tweaking needed to reach the desired effect and be completely flawless, but for the simple implementation you could go with this.

The signature for this method is history.go(number|URL) from (w3school) . So you can use a string parameter instead of number, and if (in some manner) you know which was the url for page2 you can use it.

history.go("http://localhost/page2");

when page is loaded,record now history.length in a js object. when you want back to page1 ,history.go(record-history.length-1)。 I test it work well.but i dont know whether there will be something unsafe or not.

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