图片库优化

来源:互联网 发布:淘宝发布宝贝没有品牌 编辑:程序博客网 时间:2024/06/15 02:07

此次引入了许多项测试和检查,这些测试和检查能够使我的JavaScript代码能够平稳退化,代码更健壮。

当然,在实际工作中,你要确定自己是否真的需要这些检查。

思路:

1、在prepareGallery()函数中,对浏览器是否支持DOM操作,以及能否正确得到id作了检查,如返回false则退出函数;

2、在prepareGallery()函数中,通过验证showPic的返回值,以便决定是否阻止默认行为。

3、在showPic(whichpic)函数中,对能否正确得到id以及图片节点名称是否为IMG,以及a标签是否有title属性,p标签的第一个子节点是否为文本节点,作了检查。

代码:

<body><h1>Snapshots</h1><ul id="imagegallery"><li><a href="img/024f78f0f736afc396060dbbb119ebc4b64512e1.jpg" title="picture1">Fireworks</a></li><li><a href="img/1593169_220319045543_2.jpg" title="picture2">Coffee</a></li><li><a href="img/2443543_101726406131_2.jpg" title="picture3">Rose</a></li><li><a href="img/3302397_195205012871_2.jpg" title="picture4">Big Ben</a></li><li><a href="img/u=2434715800,1445986251&fm=23&gp=0.jpg" title="picture5">hhhh</a></li></ul><!--占位符图片--><img src="img/u=2398556927,124101125&fm=23&gp=0.jpg" id="placeholder" alt="my image gallery" /><!--图片描述--><p id="description">Choose an image.</p><script type="text/javascript">//显示图片函数function showPic(whichpic) {if(!document.getElementById("placeholder")) return false;var source = whichpic.getAttribute("href");var placeholder = document.getElementById("placeholder");if(placeholder.nodeName != "IMG") return false;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");if(description.firstChild.nodeType == 3) {description.firstChild.nodeValue = text;}}return true;}function prepareGallery() {if(!document.getElementsByTagName || !document.getElementById) return false;if(!document.getElementById("imagegallery")) return false;var gallery = document.getElementById("imagegallery");var links = gallery.getElementsByTagName("a");for(var i = 0; i < links.length; i++) {links[i].onclick = function() { //在事件执行时创建匿名函数//return !showPic(this);return showPic(this) ? false : true;//先执行showPic(),然后验证showPic的返回值,以便决定是否阻止默认行为//在onclick事件处理函数所触发的JS代码里加一条return false语句,就可以防止用户被带到目标链接窗口。}}}window.onload = function() {prepareGallery();}</script></body>




0 0
原创粉丝点击