Home > Web Front-end > H5 Tutorial > body text

html5 custom attributes: how to get custom attribute values ​​(with code)

不言
Release: 2018-08-09 14:15:36
Original
5803 people have browsed it

This article introduces you to html5 custom attributes: how to obtain custom attribute values ​​​​(with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Custom attributes:

In HTML5 we can customize attributes, the format is as follows data-*="", for example: data-info="I am a custom attribute", through Node.dataset['info'] We can get the custom attribute value.

When we set the format as follows, we need to use camel case format to get it correctly: data-my-name="itcast", get Node.dataset['myName']

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--定义-->
<!--规范:
1.data-开头
2.data-后必须至少有一个字符,多个单词使用-连接
建议:
1.名称应该都使用小写--不要包含任何的大写字符
2.名称中不要有任何的特殊符号
3.名称不要副作用纯数字-->
<p data-school-name="itcast">传智播客</p>
<p data-name="itcast">传智播客</p>

<!--取值-->
<script>
    window.onload=function(){
        var p=document.querySelector("p");
        /*获取自定义属性值*/
        /*将data-后面的单词使用camel命名法连接:必须使用camel合法法获取值否则有可能无法获取到值*/
        //var value=p.dataset["schoolname"];//data-schoolname    就是相当于上面的代码块来着同一个意思来着
        var value=p.dataset["schoolName"];//data-school-name     里面的取值必须第二个单词。的第一个字母必须是大写字母来着
        console.log(value);
    }
</script>
</body>
</html>
Copy after login

Related articles Recommended:

Detailed analysis of the for attribute of the

How to solve the problem of label nesting in html

The above is the detailed content of html5 custom attributes: how to get custom attribute values ​​(with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template