js实现后退
使用 window.history.back() 方法
通过调用 window.history.back() 可以模拟浏览器的后退按钮行为,返回上一页。这是最直接的方法。
window.history.back();
监听按钮点击事件
在 HTML 中绑定按钮点击事件,触发后退操作。

<button id="backButton">返回</button>
<script>
document.getElementById('backButton').addEventListener('click', () => {
window.history.back();
});
</script>
检查历史记录长度
在执行后退操作前,可以通过 window.history.length 检查是否有可返回的历史记录。
if (window.history.length > 1) {
window.history.back();
} else {
console.log('没有可返回的页面');
}
使用 window.history.go()
window.history.go(-1) 与 window.history.back() 效果相同,但可以指定后退的步数。

window.history.go(-1);
处理无法后退的情况
在某些情况下(如通过链接直接打开页面),可能没有历史记录,此时可以跳转到指定页面。
function goBack() {
if (window.history.length > 1) {
window.history.back();
} else {
window.location.href = '/'; // 跳转到首页或其他默认页面
}
}
结合路由库(如 React Router)
在使用前端路由库时,后退功能可能需要调用路由提供的方法。
import { useNavigate } from 'react-router-dom';
function BackButton() {
const navigate = useNavigate();
return <button onClick={() => navigate(-1)}>返回</button>;
}






