Home  >  Article  >  Web Front-end  >  Detailed introduction of H5data-* attributes

Detailed introduction of H5data-* attributes

零下一度
零下一度Original
2017-07-18 13:34:052512browse

H5 added data-* attributes, which is very convenient

data-* attributes: Custom attributes to store data, data-value, the value can be any string.

Get the value:

var el = document.getElementById('div')    
console.log(el.getAttribute('data-created-time'))

Set the value:

var el = document.getElementById('div')    
el.setAttribute('data-created-time','星期一')

js can use the dataset attribute to access the value of the data-attribute

<div id=&#39;div&#39; data-mei=&#39;47&#39; data-tree-height=&#39;2.4m&#39;></div>    
var div= document.getElementById(&#39;tree&#39;)    
console.log(div.dataset.mei) // &#39;47&#39;   获取值    
console.log(tree.dataset.treeHeight) // &#39;2.4m&#39;    
tree.dataset.plantHeight = &#39;3m&#39;  //设置值

Use obj.data in jQuery ("property value") Gets and sets the value of data.

But the problem of lower case is often ignored. H5 requires all attribute names to be lower case. The habit of camel case naming is broken.

The test code is as follows:

100db36a723c770d327fc0aef2ce13b193f0f5c25f18dab9d176bd4f6de5d30e9c79b3518b1b71a70ce34ef6159b125d2cacc6d41bbb37262a98f745aa00fbf08019067d09615e43c7904885b5246f0a$(document).ready(function(){
  $("#btn2").click(function(){
    alert($("div").data("id"));
    alert($("div").data("Id"));
    alert($("div").data("otherId"));
    alert($("div").data("OtherId"));
    alert($("div").data("OTHERID"));var datas = $("div").data();
  });
});2cacc6d41bbb37262a98f745aa00fbf09c3bca370b5104690d9ef395f2c5f8d16c04bd5ca3fcae76e30b72ad730ca86dfa1cdecaa9f71d90ec149b54d5226970alert65281c5ac262bf6d81768915a4a77ac0690940018d41b49f647dca31e51d98eb16b28748ea4df4d9c2150843fecfba6836cc49f0c466276486e50c850b7e495673a6ac4ed44ffec12cee46588e518a5e
## The value from #alert is unexpected. After obtaining all data values ​​through the data() method, you can see the following results:

Summary: Follow the standards Writing method

1. data-* All characters must be lowercase.

  2. Multiple words are separated by horizontal lines. For example,

data-other-id => otherId will remove the horizontal lines and capitalize the first letter when reading the attribute.

The above is the detailed content of Detailed introduction of H5data-* attributes. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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