data-属性

dataset

  1. 能设置,也能获取
  var dom = document.getElementById("box");
      dom.dataset.myAge = 22; 
      //myAge的到的驼峰写法会自动转化为连接符号[data-my-age]
      console.log(dom.dataset.myAge); //22
  1. 使用dataset设置的一定会有data-部分

使用css设置为
[data-my-age] { color: blue; }

getAttribute/setAttribute

      dom.setAttribute("data-name","xin");
      dom.setAttribute("age",23);
      dom.setAttribute("dataName","xin");
      //[dataname="xin"]--驼峰自动转化为小写
      //[data-name="xin"]-[age="23"]-可以直接设置属性,可以没有data
      console.log(dom.getAttribute("data-my-age"))//22
      console.log(dom.getAttribute("dataMyAge"))//null
      console.log(dom.getAttribute("dataName"))//"xin"
      //会自动转化为小写,得到对应的属性
      //获得属性必须用-连接,用驼峰得不到数据

有一定的兼容性问题,慎重使用

原文地址:https://www.cnblogs.com/selfxin/p/5420193.html