如何在 JavaScript 中載入歷史列表中的下一個 URL?


在本教程中,我們將學習如何在 JavaScript 中載入歷史列表中的下一頁。

JavaScript 中的 Window 物件訪問瀏覽器中的視窗。此物件包含執行任務所需的許多屬性和方法。Window 物件還可以從瀏覽器視窗檢索資訊。

每個瀏覽器中都有一個 history 棧,用於儲存使用者訪問的頁面。要訪問此歷史棧,我們可以使用 history 物件,它是 Window 物件的屬性。透過訪問瀏覽器中的歷史記錄,我們可以轉到使用者訪問的下一個或上一個頁面。

讓我們看一下如何在 JavaScript 中載入歷史列表中的下一頁。

以下是 history 物件中用於在 JavaScript 中載入歷史列表中的下一頁的方法/函式:

  • history.forward() 方法

  • history.go() 方法

使用 history.forward() 方法

history.forward() 方法用於載入使用者先前訪問的下一頁。

但是,只有當下一頁存在於瀏覽器中的歷史棧中時,它才有效。

使用此方法與單擊瀏覽器中的 forward 按鈕相同。

使用者可以按照以下語法使用 history 物件中的 forward() 方法來載入歷史列表中的下一頁。

.
window.history.forward();
OR
history.forward();

示例 1

在以下示例中,我們使用了 forward() 方法來載入瀏覽器中歷史列表中的下一頁

<html> <body> <h3> Load next page in the history list using the <i> history.forward() </i> method</h3> <button onclick="goForward()">go forward</button> <p id="output"> </p> <script> function goForward() { window.history.forward(); document.getElementById("output").innerHTML = "You will have forwarded to next page if it exists"; } </script> </body> </html>

在上面的示例中,使用者可以看到我們使用了 forward 方法來點選按鈕。但是,只有當頁面存在於瀏覽器中的歷史棧中時,頁面才能導航到下一頁。

您可以點選此頁面上的任何連結,返回並執行程式以檢查 history.forward() 方法如何工作。

使用 history.go() 方法

history.go() 方法用於透過其編號載入頁面。我們必須將其引數作為歷史記錄中頁面的頁碼提供。頁碼可以是負數或正數,具體取決於它是前進頁面還是後退頁面。

使用者可以按照以下語法使用 history 物件中的 history.go() 方法來載入歷史列表中的下一頁。

window.history.go(page_number)
OR
history.go(page_number)

此處,page_number 是瀏覽器中歷史列表中頁面的頁碼。

要使用 history.go() 方法轉到下一頁,我們可以將 1 作為引數 page_number 傳遞。請參見以下語法:

window.history.go(1)
OR
history.go(1)

示例 2

在以下示例中,我們使用了 history.go() 方法來載入瀏覽器中歷史列表中的下一頁。

<html> <body> <h3> Load the next page in the history list using the <i> history.go() </i> method </h3> <p> Click the "go" button to load next page in the history</p> <button onclick = "go()">go</button> <p id = "output"> </p> <script> function go(){ window.history.go(1); document.getElementById("output").innerHTML = "You will have forwarded to next page if it exists"; } </script> </body> </html>

在本教程中,我們學習了兩種方法,我們可以使用它們來載入 JavaScript 中歷史列表中的下一頁。在這些方法中,history.forward() 是 history 物件中載入歷史列表中的下一頁的方法。history.go() 是 history 物件中載入下一頁的方法,同時新增“1”作為引數。

更新於: 2022年9月14日

667 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.