为了账号安全,请及时绑定邮箱和手机立即绑定

看JavaScript DOM编程艺术这本书,发现按照书上的敲的JS代码无法实现功能,求指点问题出在哪(附代码)?

看JavaScript DOM编程艺术这本书,发现按照书上的敲的JS代码无法实现功能,求指点问题出在哪(附代码)?

小布ever 2016-09-25 22:49:48
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript" src="scripts/JSscript.js"></script> </head> <body> <div id="prepareGallery"> <ul> <li><a href="images/zhou_1.jpg" title="zhou1">周杰伦1</a></li> <li><a href="images/zhou_2.jpg" title="zhou2">周杰伦2</a></li> <li><a href="images/zhou_3.jpg" onClick="showPic(this);return false;" title="zhou3">周杰伦3</a></li> </ul> <img src="images/eg.jpg" alt="my image gallery" id="placeholder" /> <p id="description">choose my image</p> </div> </body> </html>window.onload=prepareGallery(); function prepareGallery(){ if(!document.getElementsByTagName) return false; if(!document.getElementById) return false; if(!document.getElementById('prepareGallery')) return false; var gallery=document.getElementById('prepareGallery'); var links=gallery.getElementsByTagName('a'); for(var i=0;i<links.length;i++){ links[i].onClick=function(){ return !showPic(this); } } } function showPic(whichpic){ if(!document.getElementById('placeholder')) return false; var source=whichpic.getAttribute('href'); var placeholder=document.getElementById('placeholder'); placeholder.setAttribute('src',source); if(document.getElementById('description')){ if(whichpic.getAttribute('title')){ var text=whichpic.getAttribute('title'); }else{ var text=""; } var description=document.getElementById('description'); description.firstChild.nodeValue=text; } return true; }上面是HTML和JS的代码,在HTML代码中,第一、第二张图片无法实现功能,但是第三张图片标签中添加了(onClick="showPic(this);return false;")代码才能实现这个功能,请教下上面的代码哪里出现了问题,新人求助,万分感谢!
查看完整描述

4 回答

已采纳
?
qq_安逸_4

TA贡献12条经验 获得超5个赞

错误有两处:

首先:第一句改为window.onload=function(){prepareGallery();}或window.onload=prepareGallery;表示将prepareGallery函数绑定在window.onload,即在页面加载完成后执行prepareGallery函数。 

像你这样写表示:先执行prepareGallery函数,将返回结果赋给window.onload。

其次links[i].onclick=function(){}这句的onclick是小写     

之所以没有报错是因为当写成window.onload=prepareGallery();时执行在html加载之前,没有id为prepareGallery节点,所以document.getElementById('prepareGallery')是无法找到的返回null,  由于这句代码if(!document.getElementById('prepareGallery')) return false;,使得prepareGallery()直接返回false,下面的代码不会执行,也就不会报错,a标签没有被绑定点击事件,相当于超链接,所以每次执行都会打开一个新的网页显示制定图片。



查看完整回答
1 反对 回复 2016-09-26
?
Forget_淡忘

TA贡献5条经验 获得超0个赞

onclick小写...

查看完整回答
反对 回复 2016-09-26
?
_辣子

TA贡献12条经验 获得超2个赞

links[i].onclick=function(){}这句的onclick是小写就可以了

查看完整回答
反对 回复 2016-09-26
?
小布ever

TA贡献2条经验 获得超0个赞

HTML第六行链接JS文件的代码没问题,在Firefox和360安全浏览器中运行都不行。。。

查看完整回答
反对 回复 2016-09-25
  • 4 回答
  • 0 关注
  • 2613 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信