HTML5 数据集属性dataset

  有时候在HTML元素上绑定一些额外信息,特别是JS选取操作这些元素时特别有帮助。通常我们会使用getAttribute()和setAttribute()来读和写非标题属性的值。但为此付出的代价是文档将不再是合法有效的HTML。

  对此,HTML5提供了一个解决方案。在HTML5文档中,任意以"data-"为前缀的小写的属性名字都是合法的。这些“数据集属性”将不会对其元素的表现产生影响,它们定义了一种标准的、附加额外数据的方法,并不是在文档合法性上做出让步。

  HTML5还在Element对象上定义了dataset属性。该属性指代一个对象,它的各属性对应于去掉前缀的data-属性。因此dataset.x应该保存data-x属性的值。带连字符的属性对应于驼峰命名法属性名。如Element属性data-jquery-test在js中对应于dataset.jqueryTest属性

  注意,dataset属性是Element的data-属性的实时、双向接口。设置或删除dataset的一个属性就等同于设置或移除对应元素的data-属性。

var top1=document.getElementById("top1");
var ds=top1.dataset; //Element为<span id="top1" data-jquery-test="lalala">你好!</span> console.log(ds.jqueryTest);//lalala ds.jqueryTest='hello!'; //Element为<span id="top1" data-jquery-test="hello!">你好!</span> console.log(top1.getAttribute("data-jquery-test"));//hello! top1.setAttribute("data-jquery-test2","hello2"); //Element为<span id="top1" data-jquery-test="hello!" data-jquery-test2="hello2">你好!</span> console.log(ds.jqueryTest2);//hello2 delete ds.jqueryTest2; //<span id="top1" data-jquery-test="hello!">你好!</span> console.log(top1.getAttribute("data-jquery-test2"));//null

  来源于《JavaScript权威指南》 15.4.3

原文地址:https://www.cnblogs.com/-------perfect/p/4713010.html