使用nodeValue获取值与a标签默认跳转的冲突问题

今天看javascript DOM编程艺术(第2版)发现这样一个例子:

效果图:

完整代码:

<!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>
View Code

问题:

发现不加内容时

Uncaught TypeError: Cannot set property 'nodeValue' of null(…)

为避免这种情况,建议使用innerHTML来设置内容或是使用html5中的data-src.

posted @ 2017-05-18 15:39  划过天际  阅读(326)  评论(0编辑  收藏  举报