1.遍历某element元素获得属性时,属性包含的信息有很多来自原型链上的属性和方法,而这些信息有时候我们是不需要的。用下面的方法只获得我们手写在标签上的自己指定的信息。
2.获得我们手写在标签上的值:
<!doctype html>
<html lang="en"> <head> <title>Document</title> <script type="text/javascript" src="jquery-1.6.js"></script> </head> <body> <input type="checkbox" name="cbx_check" id="c1" value="v1" p1="p1" p2="p2" p3="p3"/> <script type="text/javascript">function getElementAttrObj(elementObj) {
var elementAttrObj = {};if(elementObj){
var el = elementObj; var atts = el.attributes; var el_specified_key_val_str = ''; for (var i =0,len = atts.length; i < len; i++) { var att = atts[i]; //console.info(att.specified+"-"+att.name + '-' + att.value ); debugger; var att_name = att.name.toLowerCase(); //规定属性 if (att.specified || att_name == 'value') { el_specified_key_val_str += ',"' + att.name + '":"' + att.value + '"'; } } //属性对象 if(el_specified_key_val_str){ el_specified_key_val_str = el_specified_key_val_str.substr(1); var el_specified_str = "{"; el_specified_str += el_specified_key_val_str; el_specified_str += "}"; elementAttrObj = eval('(' + el_specified_str + ')'); //console.info(el_specified_key_val_str); } }return elementAttrObj;
}var el = document.getElementById("c1");
var elementAttrObj = getElementAttrObj(el); var str = ""; for(p in elementAttrObj){ str += p + ":" + elementAttrObj[p] + ","; } alert(str);//jquery的方法 /* $("#c1").each(function () { var arr = []; var attrs = $(this).get(0).attributes; for (i = 0; i < attrs.length; i++) { att = attrs[i]; if (att.specified && att.name.toLowerCase().indexOf("data-") != -1) { arr.push(att.name + ":" + att.value); $(this).get(0).removeAttribute(att.name); } } var str = arr.join(""); alert(str); }) */ </script>
</body>
</html>