data-* properties in HTML5 We tend to add custom attributes to the HTML tag to store and manipulate the data as needed, and the names of our custom properties are also very strange and varied. We can get our custom properties by using the native getattribute () or the. attr () in jquery. But front-end technology is moving toward normalization. The HTML5 standard stipulates that custom properties are data-* beginning, thus distinguishing between intrinsic and custom attributes. The HTML code is as follows:
JS Code
$ (document). Ready (function () {var el = document.getElementById ("Testdiv"); Console.log (El.dataset.cname);//=> Zhang San el.dataset.cname = "ZS";//Set the value to "ZS" Console.log (el.dataset.cname);//=> "Zs" Console.log ("Traverse Testdiv's Own property"); $. Each (El.dataset, function (key, value) {Console.log (key+ ":" +value);}); /traverse its own property on Testdiv//cname:zs//ename:zhangsan//myname:my name is Zs.<span style= "White-space:pre" ></span> });
When you get the value of a custom property, use the DataSet property, and then get the value by using the name of the custom attribute (which then removes the data-prefix). The dataset is a newly added attribute in the JS5 specification for use with data-*.
With the results of each print, we need to note that: 1, if the data-is followed by "-", such as Date-e-name, "-" will be removed and converted into Camel peak-style named Ename. This is because the key of the JSON Object cannot contain "-". 2, if the word after data-is capitalized, such as MyName, it will be dumped into lowercase myName. There is no understanding of why it is converted to lowercase, and the JSON object key is case-sensitive. What is the designation of an expert?? 3, if you want to delete a data-* attribute, use delete dataset.cname or dataset.cname=null; The Data-* property looks good, but unfortunately only in Chrome 8+ Firefox (Gecko) 6.0+ Internet Explorer 11+ Opera 11.10+ Safari 6+ 's browser implements this standard. If your footsteps need to be compatible with different versions of the various mainstream browsers, use native getattribute () or the. attr () in jquery.
The Data-* property in HTML5 and the. Data () method in jquery use the