学习了
按我的理解写了一个 模拟历史列表的例子 希望能帮到世界上下一个看到这的人吧<!DOCTYPE html>
<html>
<head>
<title>History Example</title>
</head>
<body>
<button onclick="history.back()">返回</button>
<button onclick="history.forward()">前进</button>
<button onclick="history.go(-1)">使用Go(-1)方法返回</button>
<button onclick="addHistory()">模拟访问一个网址</button>
<button onclick="replaceHistory()">替换列表中当前记录</button>
<p>当前页面:<span id="current-page">Home</span></p>
<p>历史记录长度:<span id="history-length">0</span></p>
<script>
// 更新页面显示的当前 URL 和历史记录长度
function updateDisplay() {
document.getElementById("current-page").innerText = window.location.href;
document.getElementById("history-length").innerText = history.length;
}
// 模拟添加新的历史记录 小巧思之36进制包含数字与英文的随机字符串
function addHistory() {
history.pushState({}, "New Page", "?page=" + Math.random().toString(36).substring(7));
updateDisplay(); // 更新显示
}
// 替换当前的历史记录
function replaceHistory() {
history.replaceState({}, "Replaced Page", "?replaced=" + Math.random().toString(36).substring(7));
updateDisplay(); // 更新显示
}
// 监听浏览器的 "popstate" 事件,用于处理返回和前进操作
window.addEventListener("popstate", function () {
updateDisplay(); // 当用户返回或前进时,更新显示内容
});
// 初始化页面显示
updateDisplay();
</script>
</body>
</html>
|