如何在所有HTML元素上嵌入自定義資料屬性?


在本文中,我們需要在所有HTML元素上嵌入自定義資料屬性。我們可以使用HTML中的data-*屬性來實現。

HTML中的data-*屬性用於自定義網頁或應用程式私有的資料。此屬性向HTML元素新增自定義值。

HTML中的data-*屬性由兩部分組成:

  • 屬性值可以是任何字串。

  • 屬性名稱應僅包含小寫字母,並且在“data-”字首後必須至少包含一個字元。

此資料通常用於JavaScript中以改善使用者體驗。以下是將自定義資料屬性嵌入HTML元素的示例。

示例1

在這個例子中,

  • 我們列出了三種(服裝)商品,並附加了自定義的data-iddata-price資料。

  • 此處,資料屬性對使用者不可見。

  • 雖然使用者看不到這些值,但這些值會存在於文件中。

<!DOCTYPE html> <html> <head> <title>How do we embed custom data attributes on all HTML elements? </title> </head> <body> <ul> <li data-id="1" data-price="INR 1899">Shirt</li> <li data-id="2" data-price="INR 2799">Pant</li> <li data-id="3" data-price="INR 4599">Jacket</li> </ul> </body> </html>

這些值沒有顯示,因為我們沒有提取我們指定的自定義屬性。

示例2

在這個例子中,

  • 我們在HTML表格內建立了四個帶有標籤的連結。

  • 每個元素都有一個自定義的data-plyr-type屬性,其中包含播放器姓名。

  • 我們使用了onClick事件來提取自定義屬性。

  • 每當我們點選這些元素時,JavaScript函式就會提取並顯示球員的國家名稱。

<!DOCTYPE html> <html> <head> <script> function showData(plyr) { var players = plyr.getAttribute("data-plyr-type"); alert(plyr.innerHTML + " is a " + players + "."); } </script> </head> <body> <h1>Cricketers!</h1> <p>Click on a player to see which team he belongs to:</p> <table border=2 px;> <caption>Players</caption> <tr> <td onclick="showData(this)" id="owl" data-plyr-type="Afganistan player">Rashid khan</td> <td onclick="showData(this)" id="owl" data-plyr-type="Pakistan player">Babar azam</td> </tr> <tr> <td onclick="showData(this)" id="salmon" data-plyr-type="England player">Jos Buttler</td> <td onclick="showData(this)" id="salmon" data-plyr-type="Australia player">Steve smith</td> </tr> <tr> <td onclick="showData(this)" id="tarantula" data-plyr-type="India player">Jasprit bumrah</td> <td onclick="showData(this)" id="tarantula" data-plyr-type="West indies player">Jason holder</td> </tr> </table> </body> </html>

正如我們在輸出中看到的,當用戶點選任何板球運動員的表格資料時,自定義屬性將被提取並顯示該特定球員的國家名稱。

更新於:2022年11月8日

501 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.