JavaScript学习系列4 案例研究:图片库改进版
优秀的网页应该要支持以下情况
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")) {
var text = whichpic.getAttribute("title")?whichpic.getAttribute("title"):"";
var description = document.getElementById("description");
if(description.firstChild.nodeType == 3) {
description.firstChild.nodeValue = text;
}
}
return true;
}
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() {
return showPic(this)?false:true;
}
}
}
- 平稳退化:当JavaScript功能被禁用,用户也可以实现基本功能。
- JavaScript与HTML标记应该要分离。
- 添加事件处理函数。检查当前浏览器是否支持我们使用的函数。
- 结构化程序设计。函数应该只有一个入口和一个出口。但实际工作中,过分拘泥于这项原则往往会使代码变得难以阅读。如果函数有多个出口,我们应该把这些出口集中在开头部分。
- 网页加载完毕后再执行JavaScript函数
修改后的js为
window.onload = addLoadEvent(prepareGallery);
function addLoadEvent(func) {
var oldload = window.onload;
if(typeof window.onload != 'function') {
window.onload=func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function addLoadEvent(func) {
var oldload = window.onload;
if(typeof window.onload != 'function') {
window.onload=func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
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")) {
var text = whichpic.getAttribute("title")?whichpic.getAttribute("title"):"";
var description = document.getElementById("description");
if(description.firstChild.nodeType == 3) {
description.firstChild.nodeValue = text;
}
}
return true;
}
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() {
return showPic(this)?false:true;
}
}
}