nodeType属性:
元素节点的nodeType属性值为1;
属性节点的nodeType属性值为2;
文本节点的nodeType属性值为2;
<!doctype html> <html> <head> <meta charset="utf-8"> <title>图片库</title> <link rel="stylesheet" href="layout.css" type="text/css" media="screen"> </head> <body> <h1>快照</h1> <ul id="imagegallery"> <li> <a href="images/冰女.jpg" title="冰女">冰女</a> </li> <li> <a href="images/海民.jpg" title="海民">海民</a> </li> <li> <a href="images/小娜迦.jpg" title="小娜迦">小娜迦</a> </li> </ul> <img src="images/placeholder.jpg" id="placeholder" alt="my image gallery"> <p id="description">选择一个图片</p> <script type="text/javascript" src="showPic.js"></script> </body> </html>
function prepareGallery(){ if(!document.getElementsByTagName||!document.getElementById||!document.getElementById("imagegallery"))return false;//检查当前浏览器是否理解getElementsByTagName和getElementById,检查当前网页是否存在一个id为imagegallery的元素。 var gallery=document.getElementById("imagegallery");//找到imagegallery元素 var links=gallery.getElementsByTagName("a");//找到imagegallery元素中所有链接 for(var i=0;i<links.length;i++){ links[i].onclick=function(){ return showPic(this); } } } function showPic(whichpic) { if (!document.getElementById("placeholder")) return true; var source = whichpic.getAttribute("href"); var placeholder = document.getElementById("placeholder"); placeholder.setAttribute("src",source); if (!document.getElementById("description")) return false; if (whichpic.getAttribute("title")) { var text = whichpic.getAttribute("title"); } else { var text = ""; } var description = document.getElementById("description"); if (description.firstChild.nodeType == 3) {//检查description的第一个子元素是否是一个文本节点,文本节点的nodeType属性值等于3 description.firstChild.nodeValue = text; } return false; } function addLoadEvent(func){ var oldonload=window.onload; if(typeof window.onload !='function'){ window.onload=func; }else{ window.onload=function(){ oldonload(); func(); } } }//在页面加载完毕时执行函数,需要执行的函数以addLoadEvent(函数名)放在后面 addLoadEvent(prepareGallery); /*function countBodyChildren(){ var body_element=document.getElementsByTagName("body")[0]; alert (body_element.childNodes.length); } window.onload=countBodyChildren; 在页面加载时执行,显示body元素的子元素的总个数*/
JavaScript DOM 编程艺术书上的showPic函数有些问题,我这段代码是从图灵图书下的源代码