窗口历史记录对象
在 JavaScript 中,窗口 'history' 对象包含有关浏览器会话历史记录的信息。它包含当前会话中访问的 URL 数组。
'history' 对象是 'window' 对象的一个属性。history 属性可以在不引用其所有者对象(即 window 对象)的情况下访问。
使用 'history' 对象的方法,你可以转到浏览器会话的 previous、following 或特定的 URL。
History 对象方法
窗口历史记录对象提供了有用的方法,允许我们在历史记录列表中来回导航。
按照下面的语法在 JavaScript 中使用 'history' 对象。
window.history.methodName();
OR
history.methodName();
您可以使用 'window' 对象来访问 'history' 对象。
JavaScript 历史记录 back() 方法
history 对象的 JavaScript back() 方法加载 history 列表中的前一个 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 历史记录 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 历史记录 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 对象方法列表
history 对象包含以下 3 种方法。
方法 | 描述 |
---|---|
back() | 会将您带到上一个网页. |
forward() | 将带您到下一个网页。 |
go() | 可以将您带到特定的网页。 |