JavaScript - History 对象
Window History 对象
在 JavaScript 中,Window 的"history"对象包含浏览器会话历史记录信息。它包含当前会话中访问过的 URL 数组。
"history"对象是"window"对象的一个属性。访问 history 属性时,无论是否引用其所属对象(即 window 对象),都可以访问。
使用"history"对象的方法,您可以跳转到浏览器会话的上一个、下一个或特定的 URL。
History 对象的方法
Window History 对象提供了一些实用的方法,允许我们在历史记录列表中来回导航。
请按照以下语法在 JavaScript 中使用"history"对象。
window.history.methodName(); 或 history.methodName();
您可以使用"window"对象访问"history"对象。
JavaScript History back() 方法
history 对象的 JavaScript back() 方法会加载历史记录列表中的上一个 URL。
语法
请按照以下语法使用 history back() 方法。
history.back();
示例
在下面的代码输出中,您可以点击"返回"按钮返回上一个 URL。它的作用相当于浏览器的返回按钮。
<html>
<body>
<p> Click "Go Back" button to load previous URL </p>
<button onclick="goback()"> Go Back </button>
<p id = "output"> </p>
<script>
function goback() {
history.back();
document.getElementById("output").innerHTML +=
"You will have gone to previous URL if it exists";
}
</script>
</body>
</html>
JavaScript History forward() 方法
history 对象的 forward() 方法会将您带到下一个 URL。
语法
请按照以下语法使用 forward() 方法。
history.forward();
示例
在下面的代码中,点击按钮即可转到下一个 URL。它的作用相当于浏览器的前进按钮。
<html>
<body>
<p> Click "Go Forward" button to load next URL</p>
<button onclick = "goforward()"> Go Forward </button>
<p id = "output"> </p>
<script>
function goforward() {
history.forward();
document.getElementById("output").innerHTML =
"You will have forwarded to next URL if it exists."
}
</script>
</body>
</html>
JavaScript History 的 go() 方法
history 对象的 go() 方法会将您带到浏览器会话的特定 URL。
语法
请按照以下语法使用 go() 方法。
history.go(count);
在上述语法中,"count"是一个数值,表示您要访问的页面。
示例
在下面的代码中,我们使用 go() 方法从当前网页跳转到上一页。
<html>
<body>
<p> Click the below button to load 2nd previous URL</p>
<button onclick = "moveTo()"> Move at 2nd previous URL </button>
<p id = "output"> </p>
<script>
function moveTo() {
history.go(-2);
document.getElementById("output").innerHTML =
"You will have forwarded to 2nd previous URL if it exists.";
}
</script>
</body>
</html>
示例
在下面的代码中,我们使用 go() 方法从当前网页移动到上一页。
<html>
<body>
<p> Click the below button to load 2nd next URL</p>
<button onclick = "moveTo()"> Move at 2nd next URL </button>
<p id = "output"> </p>
<script>
function moveTo() {
history.go(2);
document.getElementById("output").innerHTML =
"You will have forwarded to 2nd next URL if it exists.";
}
</script>
</body>
</html>
以下是完整的窗口历史记录对象参考,包括属性和方法 -
History 历史记录对象属性列表
历史记录对象仅包含"length"属性。
| 属性 | 描述 |
|---|---|
| length | 返回对象的长度,表示对象中存在的 URL 数量。 |
History 历史记录对象方法列表
历史记录对象包含以下 3 个方法。
| 方法 | 描述 |
|---|---|
| back() | 返回上一个网页。 |
| forward() | 返回下一个网页。 |
| go() | 返回特定网页。 |

