今天看javascript DOM編程藝術(第2版)發現這樣一個例子:javascript
效果圖:html
完整代碼:html5
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #placeholder{ width: 300px; height: 200px; } img{ display: block; } </style> </head> <body> <h3>圖片展現</h3> <ul> <li><a href="images/logo.png" title="天靈圖標">天靈圖標</a></li> <li><a href="images/panda.png" title="熊貓圖標" >熊貓圖標</a></li> <li><a href="images/gameLogo.png" title="遊戲圖標">遊戲圖標</a></li> </ul> <img id="placeholder" src="images/placeholder.jpg" alt="mypic"> <p id="description">選擇一張圖片</p> </body> <script> function showPic(whichPic){ var source=whichPic.getAttribute('href'); var placeholder=document.getElementById('placeholder'); placeholder.setAttribute("src",source); var text =whichPic.getAttribute('title'); var description=document.getElementById('description'); // description.childNodes[0].nodeValue= text; description.firstChild.nodeValue= text; // description.innerHTML=text; } var dianji=document.getElementsByTagName('a'); for(var i=0;i<dianji.length;i++){ dianji[i].onclick=function(){ showPic(this); return false; } } </script> </html>
問題:java
發現不加內容時node
Uncaught TypeError: Cannot set property 'nodeValue' of null(…)編程
爲避免這種狀況,建議使用innerHTML來設置內容或是使用html5中的data-src.ide