我点击一下即可更改页面上的内容。我想知道当你按下浏览器上的后退按钮时是否有办法触发效果
答案 0 :(得分:14)
您可以使用popstate事件进行排序:
window.onpopstate = function() {
alert("pop!");
}
或 jQuery :
$(window).on('popstate', function(event) {
alert("pop");
});
然而,这也会在向前导航时触发,而不仅是向后导航。
答案 1 :(得分:7)
$(function() {
if (window.history && window.history.pushState) {
window.history.pushState('', null, './');
$(window).on('popstate', function() {
// alert('Back button was pressed.');
document.location.href = '#';
});
}
});
答案 2 :(得分:3)
使用此代码检测浏览器后退按钮事件
<script>
if (performance.navigation.type == 2) {
alert("Back button clicked");
}
</script>
答案 3 :(得分:1)
你可以简单地在JQuery中触发“popState”事件,例如:
$(window).on('popstate', function(event) {
alert("pop");
});
这对你提出的问题已经足够了......但是这里有很少的窗口事件加上......
$(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..
答案 4 :(得分:0)
您可以使用 popstate
来检测何时回来。
$(window).on('popstate', function(event) {
alert("You are going to back page. Can work that?");
});
button {
padding: 5px;
border-radius: 5px;
background: limegreen;
border: 1px limegreen solid;
color: white;
width: 100px;
}
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<button onclick="window.history.back()">Back</button>
<p>Or you can click on browser back button.</p>
</body>
</html>
谢谢你,如果工作。!.?