JavaScript DOM编程艺术-JavaScript图片库

通过点击链接可在一个网页上变换显示的图片。

test.html文件

<!document html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>image</title>
</head>
<body>
	<h1>show my picture</h1>
	<ul id="imagegallery">
		<li>
			<a href="1.jpg" title="a">aaaa</a>
		</li>
		<li>
			<a href="2.jpg" title="b">bbbb</a>
		</li>
		<li>
			<a href="3.jpg" title="c">cccc</a>
		</li>
		<li>
			<a href="4.jpg" title="d">dddd</a>
		</li>
	</ul>
	<img id="place" src="1.jpg" alt="my image"/>
	<p id="des">choose a title</p>
	<script type="text/javascript" src="addLoadEvent.js"></script>	
	<script type="text/javascript" src="show.js"></script>
</body>
</html>

show.js文件

// window.onload = function(){
	// prepareGallery();
// }
addLoadEvent(prepareGallery);

function prepareGallery(){
	if(!document.getElementsByTagName) return false;
	if(!document.getElementById) return false;
	if(!document.getElementById("imagegallery")) return false;
	var links=document.getElementById("imagegallery").getElementsByTagName("a");
	for(var i=0; i<links.length; i++){
		links[i].onclick = function(){
			return !showPic(this);
		}
	}
}
function showPic(whichpic){
	var source = whichpic.getAttribute("href");
	var place = document.getElementById("place");
	place.setAttribute("src",source);
	var text = whichpic.getAttribute("title");
	var des = document.getElementById("des");
	des.firstChild.nodeValue = text;
	return true;
}

addLoadEvent.js文件

function addLoadEvent(func){
	var oldonload = window.onload;
	if(typeof window.onload != 'function'){
		window.onload = func;
	}
	else{
		window.onload = function(){
			oldonload();
			func();
		}
	}
}


如果同时定义两个函数他们都要在页面加载时得到执行怎么办呢?
方法1:
window.onload = function(){
	first.Function();
	secondFunction();
}

方法二:

使用addLoadEvent函数,如实例。

addLoadEvent(firstFunction);

addLoadEvent(secondFunction);

function addLoadEvent(func){
	var oldonload = window.onload;
	if(typeof window.onload != 'function'){
		window.onload = func;
	}
	else{
		window.onload = function(){
			oldonload();
			func();
		}
	}
}




你可能感兴趣的:(JavaScript DOM编程艺术-JavaScript图片库)