在本文中,我们需要在所有HTML元素上嵌入自定义数据属性。我们可以使用HTML中的data-*属性来实现。
在HTML中,data-* 属性用于自定义仅对网页或应用程序私有的数据。该属性可为HTML元素添加自定义值。
HTML中的data-*属性由两部分组成−
这些数据通常在JavaScript中用于改善用户体验。以下是在HTML元素上嵌入自定义数据属性的示例。
示例1
在这个例子中,
<!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
在这个例子中,
We’ve created four links with tags inside the HTML table.
<!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>
正如我们在输出中所看到的,当用户点击任何一位板球运动员的表格数据时,将提取自定义属性并显示特定球员的国家名称。
以上就是我们如何在所有HTML元素上嵌入自定义数据属性?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。