
在本文中,我们需要在所有HTML元素上嵌入自定义数据属性。我们可以使用HTML中的data-*属性来实现。
在HTML中,data-* 属性用于自定义仅对网页或应用程序私有的数据。该属性可为HTML元素添加自定义值。
HTML中的data-*属性由两部分组成−
属性值可以是任意字符串。
立即学习“前端免费学习笔记(深入)”;
属性名称应只包含小写字母,并且在前缀"data-"之后必须至少有一个字符。
这些数据通常在JavaScript中用于改善用户体验。以下是在HTML元素上嵌入自定义数据属性的示例。
在这个例子中,
我们已列出三个带有自定义 data-id 和 data-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>
这些值没有显示出来,因为我们没有提取我们指定的自定义属性。
在这个例子中,
We’ve created four links with tags inside the HTML table.
每个元素都有一个自定义的data-plyr-type属性,其中包含一个播放器名称。
我们使用了 onClick 事件来提取自定义属性。
每当我们点击 <a> 元素时,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>
正如我们在输出中所看到的,当用户点击任何一位板球运动员的表格数据时,将提取自定义属性并显示特定球员的国家名称。
以上就是我们如何在所有HTML元素上嵌入自定义数据属性?的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号