JavaScript技巧——变量Dom对象的所有属性
DOM对象的HTML:
<button id="btnToggleState" onclick="toggleStateManagement()">Disable State</buttom>
1,遍历DOM对象所具有的属性(全部,不管是否在HTML tag中是否设置)
<!DOCTYPE html>
<html>
<body>
<button id="btnToggleState" onclick="toggleStateManagement()">
Disable State
</button>
</body>
<script>
var obj = document.getElementById("btnToggleState");
var s = "";
for (var elem in obj) {
s += elem + "\n";
}
alert(s);
</script>
</html>
结果:
2.遍历DOM对象在HTML中设置过的属性:
每一个attribute属性有一个附加属性specified,当属性是HTML Element的属性(指写在代码中可见的),或者是通过setAttribute方法进行的添加的时候,它的值为 true。
<!DOCTYPE html>
<html>
<body>
<button id="btnToggleState" onclick="toggleStateManagement()">
Disable State
</button>
</body>
<script>
// var obj = document.getElementById("btnToggleState");
// var s = "";
// for (var elem in obj) {
// s += elem + "\n";
// }
// alert(s);
var obj = document.getElementById("btnToggleState");
var pairs = new Array();
for (var i = 0, len = obj.attributes.length; i < len; i++) {
var name = obj.attributes[i].nodeName;
var value = obj.attributes[i].nodeValue;
if (obj.attributes[i].specified) {
pairs.push(name + "=\' " + value + "\' ")
}
}
alert(pairs);
</script>
</html>
结果如下: