html5 data-*自定义属性取值
demo:
<!DOCTYPE HTML> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="expires" content="0" /> <script src="<%=path%>/js/jquery/jquery-1.8.3.min.js"> </script> </head> <body> <div id="divDom" data-name="userName" data-age="26" data-address="北京市">data-test</div> </body> <script type="text/javascript"> $(function(){//$(element).data(keyName),jquery也提供了兼容方法。 var divDom = document.getElementById('divDom'),dataSet = get_dataset(divDom); console.info("name:"+dataSet.name); console.info("age:"+dataSet["age"]); }); //带兼容的函数 function get_dataset(ele){ if(ele.dataset) return ele.dataset; else{ //以下是兼容代码 var dataset = {}; var ele_split = ele.outerHTML.split(" "); for(var i = 0,element; i < ele_split.length; i++) { element = ele_split[i]; if (element.substring(0,4) == "data") { if (element.indexOf(">") != -1) { element = element.split(">")[0]; }; ele_key=element.split("=")[0].slice(5); ele_value=element.split("=")[1].slice(1,-1); if(ele_key.indexOf("-") == -1){ dataset[ele_key] = ele_value; }else{ ele_keys=ele_key.split("-"); ele_key=ele_keys[0]; for(i=1;i<ele_keys.length;i++){ ele_key+=replaceReg(ele_keys[i]); } } }; } return dataset; } } //正则表达式变换首字母大写 function replaceReg(str){ var reg = /\b(\w)|\s(\w)/g; str = str.toLowerCase(); return str.replace(reg,function(m){return m.toUpperCase()}) } </script> </html>