Jquery when back button is pressed

亡梦爱人 提交于 2019-11-30 01:48:34

问题


I have a click that changes things on the page when you click it. I was wondering if there was a way to trigger an effect when you press the back button on the browser


回答1:


You can sort of do it using the popstate event:

window.onpopstate = function() {
  alert("pop!");
}

or in jQuery:

$(window).on('popstate', function(event) {
 alert("pop");
});

However this will also trigger when navigating forward, not only backward.




回答2:


Disable back url

$(function() {
    if (window.history && window.history.pushState) {
        window.history.pushState('', null, './');
        $(window).on('popstate', function() {
            // alert('Back button was pressed.');
            document.location.href = '#';

        });
    }
});



回答3:


You can simply fire the “popState” event in JQuery e.g:

$(window).on('popstate', function(event) {
    alert("pop");
});

This is enough for what you asked … but here are few add on window event to go with…

$(window).on('pushstate', function(event) {
    alert("push");
}); // This one pushes u to forward page through history...

window.history.replaceState(); //work exactly like pushstate bt this one replace the history instead of creating new one...
window.history.backward(); // To move backward through history, just fire this event...
window.history.forward();// To move forward through history ...
window.history.go(-1); // Go back to one page(or whatever value u passed) through history
window.history.go(1); // Go forward to one page through history..


来源:https://stackoverflow.com/questions/17628612/jquery-when-back-button-is-pressed

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