pjax : HTML link that works like a browser back button

半城伤御伤魂 提交于 2019-12-23 13:07:02

问题


I'm using pjax for my website navigation. I need to create a HTML back button that works exactly like the browser back button. But this one should be a simple HTML link. How can I create a pjax link that navigates to the previous page?

I've searched and all the topics seem to be about browser back button, which is not what I want

This is the code that I use for my pjax navigation

 $(function() {
        $(document).pjax('.pjax', '#pjax-container', {
            fragment: '#pjax-container',
            timeout: 9000000 ,
        });
    });

回答1:


You can access the browsing history via javascript. See the documentation.

If you just want a simple back link, you can use it like this:

<a href="javascript:window.history.back();">go back</a>

or like this:

<button onclick="window.history.back()">go back</button>

Alternatively if you don't want to use window.history, your application should maintain browsing history.

You can use events from the pjax library. An example you can follow:

// Variable to control history
const myAppHistory = []

// Get current url from event before ajax and put into an variable to control the history
$(document).on('pjax:beforeSend', function(event) {
    const url = event.currentTarget.URL;
    myAppHistory.push(url);
})

// Returns last page visited
function goBack() {
    const url = myAppHistory.pop()
    if (typeof url != "undefined") {
        $.pjax({url: url, container: '#main'})  
    }
}

So you use the goBack() wherever you need it.




回答2:


If you want to create a simple HTML link that takes you to the previous page, you can use History API to accomplish that.

You can do it easily by using History API's window.history.back() method and an anchor tag like this:

<a href="javascript:window.history.back()">Back</a>

or with a button you can do it in onclick attribute like this

<button onclick="javascript:window.history.back()">Back</button>



回答3:


Yeah, Just define a function for that...

function goBack(){

   window.history.back();

}

And then call it like

<button onClick="goBack()">Back</button>

Or,

<a onClick="goBack()">Back</a>


来源:https://stackoverflow.com/questions/53899517/pjax-html-link-that-works-like-a-browser-back-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!