如何在 JavaScript 中獲取區域的 href 屬性的雜湊部分?


在本教程中,我們將學習如何在 JavaScript 中獲取區域的 href 屬性的雜湊部分。

HTML 元素 <area> 在影像地圖中建立了一個具有預定可點選區域的區域。影像地圖允許您將圖片的幾何區域與超文字連結相關聯。此元素只能在 < map> 元素內使用。

href 屬性提供了區域的超連結目標。如果不存在 href 屬性,則 <area> 元素不是超連結。

以下是用於在 JavaScript 中獲取區域的 href 屬性的雜湊部分的方法:

使用 HTML DOM Area 雜湊屬性

在 HTML DOM 中,DOM Area 獲取雜湊屬性用於返回 href 屬性值的錨部分。錨部分是雜湊符號 (#) 之後出現的 URL 元件。

它具有一個單值錨名稱,指定 URL 的錨部分。它生成一個字串值,該值反映 URL 的錨部分,包括雜湊符號 (#)。

語法

area_object.hash;

使用雜湊屬性呼叫 area_object 並返回包含雜湊 (#) 的 URL 的錨部分。

示例 1

在此示例中,我們使用了雜湊屬性來獲取 href 屬性的雜湊部分。id 為 "area_javascript" 的區域具有 href 屬性,當使用雜湊屬性時,其雜湊後的文字將被返回(包括雜湊)。

<html> <body> <h3>Get the hash part of the href attribute of an area using the <i>hash</i> property</h3> <img src="/javascript/images/javascript-mini-logo.jpg" alt="javascript_logo" usemap="#javascript" width="200" eight="200"> <map name = "javascript"> <area id="area_javascript" shape = "rectangle" coords = "154,150,59, 0" href = "/javascript/index.htm#overview" alt = "Team" target = "_self" > </map> <p id = "outputDiv"> </p> <script> let output = document.getElementById("outputDiv"); var area1 = document.getElementById("area_javascript").hash; output.innerHTML = "Hash : "+area1 +"<br>"; </script> </body> </html>

透過設定 HTML DOM 雜湊屬性

透過使用此雜湊屬性,可以設定 href 屬性值的錨元件。URL 錨位於雜湊符號 (#) 之後。要設定錨,請刪除雜湊符號 (#)。

語法

area_object.hash = anchor_name;

已呼叫 area_object,並且錨部分的雜湊值已設定為不同的值,如 anchor_name 中所示。

示例 2

在此示例中,我們使用了雜湊屬性來更改 URL 的錨部分。使用雜湊屬性查詢雜湊值,然後相應地更改文字。

<html> <body> <h3>Get the hash part of the href attribute of an area after setting to new has value</h3> <img src="/javascript/images/javascript-mini-logo.jpg" alt="javascript_logo" usemap="#javascript" width="200" height="200"> <map name = "javascript"> <area id="area_javascript" shape = "rectangle" coords = "154,150,59, 0" href = "/javascript/index.htm#home" alt = "Team" target = "_self" > </map> <p id = "outputDiv"> </p> <script> let output = document.getElementById("outputDiv"); // set hash property document.getElementById("area_javascript").hash = "quick_guide" output.innerHTML += "Set Hash : quick_guide"+"<br>"; var area1 = document.getElementById("area_javascript").hash; output.innerHTML += "Hash : "+area1 +"<br>"; </script> </body> </html>

在本教程中,我們學習了在 JavaScript 中獲取區域的 href 屬性的雜湊部分的兩種方法。第一種方法是使用雜湊屬性。在第二種方法中,我們使用不同的值設定雜湊屬性,然後訪問更新的雜湊值。

更新於: 2022年9月14日

582 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.