练习:利用表 11.1 里的 nodeType 信息,编写一个函数,获取页面 <body> 区域的全部 HTML 注释,把它们组合成一个字符串。给程序清单 11.2 的代码里添加一些注释,然后测试一下新函数的功能。
代码内容如下:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>nodeType Practice</title> <script> function bodyNote(){ var bodyElement = document.getElementById("b1"); var out = ""; for( var i=0; i<bodyElement.childNodes.length; i++){ var type = bodyElement.childNodes[i].nodeType; switch(type){ case 1: out += " (" + bodyElement.childNodes[i].nodeName + " '元素' " + " ) \n"; break; case 2: out += " (" + bodyElement.childNodes[i].nodeName + " '属性' " + " ) \n"; break; case 3: out += " (" + bodyElement.childNodes[i].nodeName + " '文本(包含空白)' " + " ) \n"; break; case 4: out += " (" + bodyElement.childNodes[i].nodeName + " 'CDATE区域' " + " ) \n"; break; case 5: out += " (" + bodyElement.childNodes[i].nodeName + " '实体引用' " + " ) \n"; break; case 6: out += " (" + bodyElement.childNodes[i].nodeName + " '实体' " + " ) \n "; break; case 7: out += " (" + bodyElement.childNodes[i].nodeName + " '执行指令' " + " ) \n "; break; case 8: out += " (" + bodyElement.childNodes[i].nodeName + " 'HTML注释' " + " ) \n "; break; case 9: out += " (" + bodyElement.childNodes[i].nodeName + " '文档' " + " ) \n"; break; case 10: out += " (" + bodyElement.childNodes[i].nodeName + " '文档类型(DTD)' " + " ) \n"; break; case 11: out += " (" + bodyElement.childNodes[i].nodeName + " '文档片段' " + " ) \n"; break; case 12: out += " (" + bodyElement.childNodes[i].nodeName + " '标签' " + " ) \n"; break; default: out += " (" + bodyElement.childNodes[i].nodeName + " '其他' " + " ) \n"; break; } } alert("Body区域的HTML标签注释(字符串):\n" + out); } window.onload = bodyNote; </script> </head> <body id="b1"> <h1>Things To Do</h1> <ol id="toDoList"> <li>Mow the lawn</li> <li>Clean the window</li> <li>Answer your email</li> </ol> <p id="toDoNotes">Make sure all these are completed by 8pm so you can watch the game on TV!</p> </body> </html>