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='div' data-mei='47' data-tree-height='2.4m'></div> var div= document.getElementById('tree') console.log(div.dataset.mei) // '47' 获取值 console.log(tree.dataset.treeHeight) // '2.4m' tree.dataset.plantHeight = '3m' //设置值
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:
<html><head><script type="text/javascript" src="jquery-1.9.1.js?1.1.11"></script><script type="text/javascript">$(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(); }); });</script></head><body><button id="btn2">alert</button><div data-id="小写id" data-Id="大写ID" data-otherId="驼峰id" data-other-id="横线id"></div></body></html>
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!