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>
结果如下:
相关推荐
huaoa 2020-09-14
爱读书的旅行者 2020-07-07
liaoxuewu 2020-05-19
luvhl 2020-08-17
liaoxuewu 2020-07-08
liaoxuewu 2020-06-26
北京老苏 2020-06-25
Lophole 2020-06-14
SIMONDOMAIN 2020-06-14
luvhl 2020-06-13
SIMONDOMAIN 2020-05-31
hyMiss 2020-05-19
书虫媛 2020-05-15
liaoxuewu 2020-05-11
liaoxuewu 2020-05-10
小仙儿 2020-05-09
hyMiss 2020-05-01