如何使用 JavaScript 從 window.location(URL)中去除雜湊而不重新整理頁面?


replaceState() 方法使用作為方法引數傳遞的狀態物件、標題和 URL 替換當前歷史記錄條目。當你希望響應使用者操作來更新當前歷史記錄條目的狀態物件或 URL 時,此方法非常有用。

要移除 URL 中的雜湊,使用歷史 API 的 replaceState 方法移除雜湊位置。

語法

replaceState() 方法的語法如下所示 -

window.history.replaceState(stateObj,"unused", "url")

此函式將接受三個引數。它們是 -

  • stateObj - 此引數與傳遞給 replace 方法的歷史記錄條目關聯。此引數可以為 null。

  • URL - 如果新網址與當前網址不在同一源中,replaceState 會丟擲一個異常。

示例 1

此示例演示瞭如何在 JavaScript 中將雜湊從 URL 中去除 -

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scal=1.0"> <title>Remove Hash from URL</title> </head> <body style="text-align: align-self: start;"> <h1 style="color: orange">Tutorials Point</h1> <p>Removing the hash from window.location with JavaScript without page refresh </p> <p>modifying the current history state can also be done </p> <button onclick="modState()"> History state Modification </button> <button onclick="remHash()"> Remove hash from url </button> <script> function modState() { let stateObj = { id: "100" }; window.history.replaceState(stateObj, "Untitled-1", "/answer#Untitled-1.html"); } function remHash() { var uri = window.location.toString(); if (uri.indexOf("#") > 0) { var clean_uri = uri.substring(0, uri.indexOf("#")); window.history.replaceState({}, document.title, clean_uri); } } </script> </body> </html>

更新於: 26-8-2022

3K+ 瀏覽量

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.