本文實例講述了Javascript遞歸打印Document層次關系的方法。分享給大家供大家參考。具體如下:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>遞歸顯示節點層次關系</title> <script type="text/javascript"> var ResultStr = ""; function ListNode(node,level) { PrintInfo(node, level); level++; var nodes = node.childNodes; for (var i = 0; i < nodes.length; i++) { if (nodes[i].hasChildNodes()) { ListNode(nodes[i], level); //遞歸 } else { PrintInfo(nodes[i], level); } } } function getSpace(level) { var s = ""; for (var i = 0; i < level; i++) { s+="!----" } return s; } function PrintInfo(node, level) { ResultStr += getSpace(level) + "Name:" + node.nodeName + "...Type:" + node.nodeType + "...Value:" + node.nodeValue + "<br />"; } function getDocAllInfo() { ResultStr = ""; ListNode(document, 0); document.write(ResultStr); } </script> </head> <body> <input type="button" value="測試" onclick="getDocAllInfo()" /> <div id="divDemo">div內容</div> <table> <tr> <td>單元格1</td> <td>單元格2</td> </tr> <tr> <td>單元格3</td> <td>單元格4</td> </tr> </table> <input type="text" /> <span>我是SPAN</span> <!--我是注釋--> </body> </html>希望本文所述對大家的javascript程序設計有所幫助。