如何在 JavaScript 中獲取包含當前 URL 引數的物件?
JavaScript 是一種用途廣泛的指令碼語言,可以以多種方式使用。其中一種方法是使用它來獲取有關當前 URL 的資訊。這在許多情況下都很有用,例如當您想要建立書籤或將使用者重定向到特定頁面時。
使用 Location 物件
獲取有關當前 URL 資訊的最簡單方法是使用 **Location** 物件。此物件是 window 物件的一個屬性,包含有關當前 **URL** 的資訊。要使用它,只需使用要訪問的屬性的名稱來呼叫該物件即可。例如,要獲取 **href** 屬性,可以使用 -
var currentURL = window.location.href;
這將返回整個 URL,包括協議 **(http:// 或 https://)**、主機名、路徑和查詢字串。
如果您只需要路徑,可以使用 Location 物件的 pathname 屬性 -
var currentPath = window.location.pathname;
這將返回主機名之後的所有內容,包括查詢字串。
使用 document.URL 屬性
獲取有關當前 URL 資訊的另一種方法是使用 **document.URL** 屬性。此屬性包含當前頁面的整個 URL。要使用它,只需呼叫 -
var currentURL = document.URL;
這將返回整個 URL,包括協議 (http:// 或 https://)、主機名、路徑和查詢字串
使用 document.location 屬性
獲取有關當前 URL 資訊的另一種方法是使用 **document.location** 屬性。此屬性包含一個包含有關當前 URL 資訊的物件。要使用它,只需呼叫 -
var currentURL = document.location;
這將返回一個包含有關當前 URL 資訊的物件。該物件將具有協議 (http:// 或 https://)、主機名、路徑和查詢字串的屬性。
示例
獲取使用者輸入 URL 引數的 HTML 程式碼
以下是您可以用來獲取使用者輸入 URL 引數的完整 HTML 程式碼。您還可以在本節末尾找到一個可執行的演示。建立一個包含以下程式碼的 HTML 檔案,並在任何瀏覽器中開啟它。
<html> <head> <title>Get URL Parameters</title> </head> <body> <h1>Get URL Parameters</h1> <p> Enter a URL in the input field below and click on the "Get Parameters" button. </p> <form> <input type="text" id="url" placeholder="Enter a URL.." /> <input type="button" id="submit" value="Get Parameters" /> </form> <div id="output"></div> <script> function getParams() { // Get the URL with the query string from the input var url = document.getElementById('url').value; // Create an object with the query string parameters and their values var params = {}; var parser = document.createElement('a'); parser.href = url; var query = parser.search.substring(1); var vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); params[pair[0]] = decodeURIComponent(pair[1]); } // Display the query string parameters on the page var output = ''; for (var param in params) { if (params.hasOwnProperty(param)) { output += '<p>' + param + ': ' + params[param] + '</p>'; } } document.getElementById('output').innerHTML = output; } // Add event listener document.getElementById('submit').addEventListener('click', getParams); </script> </body> </html>
在上面的程式碼中,我們有一個輸入欄位和一個按鈕。當用戶在輸入欄位中輸入 URL 並點選“獲取引數”按鈕時,我們將呼叫 **getParams()** 函式。
此函式建立一個包含查詢字串引數及其值的物件。然後它在頁面上顯示查詢字串引數。
您還可以看到我們為按鈕的“click”事件添加了一個事件監聽器。這樣,當點選按鈕時,就會呼叫我們的 *getParams()* 函式。
在本教程中,我們學習瞭如何使用 JavaScript 獲取有關當前 URL 的資訊。我們還學習瞭如何建立一個包含查詢字串引數及其值的物件。
在本教程中,我們學習瞭如何使用 JavaScript 獲取有關當前 URL 的資訊。我們還學習瞭如何建立一個包含查詢字串引數及其值的物件。