JavaScript DOM编程艺术 学习笔记(六)图片库改进版


图片库这个例子

1。符合平稳退化

<a href = “images/fireworks.jpg” onclick = “showPic(this); return false;” title = “A fireworks display”>Fireworks</a>

即使不支持javaScript 浏览器也会打开href属性给的链接 所以符合了平稳退化


而如果用<a href = “javascript:showPic(‘images/coffee.jpg’); return false;”</a>

即选用了javaScript伪协议,则在不支持js的浏览器上运行出不来效果


<a href=“#” onclick = “showPic(‘images/coffee.jpg’); return false;”</a>

这也是不符合平稳退化的原则

因为”#”是未指向任何目标的内部链接,把href属性的值设置为”#”只是为了创建一个伪链接。实际工作都由onclick属性负责完成。


2。js没有分离 没有做向下兼容

原来是在html里直接如上在标签里写onclick事件,显然没有把html和js分离

每个li都有onclick事件 可以把ul设置一个id名为imagegallery 然后在js里拿到这个ul的所有li设置其onclick事件(下面加的那些if都是为了向下兼容)

eg: 

function prepareGallery(){

if(!document.getElementsByTagName) return false;

if(!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(){

showPic(this);

return false;

}

   }

}


function showPic(whichpic){

if(!document.getElementById(“placehoulder”)) return false;

var source = whichpic.getAttribute(“href”);

var  placeholder = document.getElementById(“placehoulder”);

placeholder.setAttribute(“src”,source);

if(!document.getElementById(“description”)){

var text = whichpic.getAttibute(“title”);

var description = document.getElementById(“description”);

description.firstChild.nodeValue = text;

}

return true;

}

3。js何时执行:

如果在onload之前执行,即在html文档完成加载之前,此时的dom是不完整的。此方法里拿到dom节点的方法正确性就不定了。所以要在网页加载完毕即所有dom都加载完毕

window.onload = function(){

firstFunction();

secondFunction();

}


因为a标签中同时存在 href onclick,如果想让 href 属性下的动作不执行,onclick 必须得到一个 false 的返回值。

这里比如当页面没有placehoulder,showPic就返回false了,这样也没有走后面的实现也不能走href的链接,没有做到平稳退化,所以应该考虑只有showPic能完整走下来的话才去禁掉href

可以改成:

links[i].onclick = function(){

return !showPic(this);

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章