<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Image Gallery</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
body{
width: 960px;
margin: 30px auto;
background: rgba(134,205,80,0.2);
}
ul{
display: inline-block;
width: 100%;
padding: 20px;
}
li{
list-style: none;
width: 20%;
float: left;
}
a{
text-decoration: none;
color: #000;
}
img{
width: 640px;
height: 400px;
}
p{
padding: 20px 0;
}
</style>
<script type="text/javascript">
function addLoadEvent(func){
var oldonload=window.onload;
if(typeof window.onload!='function'){
window.onload=func;
}else{
window.onload=function(){
oldonload();
func();
}
}
}
addLoadEvent(prepareGallery);
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')){
var text=whichpic.getAttribute('title')?whichpic.getAttribute('title'):'';
var description=document.getElementById('description');
description.firstChild.nodeValue = text;
}
return true;
}
function prepareGallery(){
if(!document.getElementsByTagName) return false;
if(!document.getElementById) return false;
if(!document.getElementById('gallery')) return false;
var gallery=document.getElementById('gallery');
var link=gallery.getElementsByTagName('a');
for(var i=0;i<link.length;i++){
link[i].onclick=function(){
return !showPic(this);
}
}
}
</script>
</head>
<body>
<h1>Image Gallery</h1>
<ul id="gallery">
<li><a href="img/2.jpg" title="image2" target="_blank">image2</a></li>
<li><a href="img/3.jpg" title="image3">image3</a></li>
<li><a href="img/4.jpg" title="image4">image4</a></li>
<li><a href="img/5.jpg" title="image5">image5</a></li>
</ul>
<img src="img/2.jpg" id="placeholder" alt="my image gallery">
<p id="description">image gallery</p>
</body>
</html>
关于addLoadEvent
addLoadEvent(prepareGallery);这一操作处
window.onload涉及到两个函数,一个是prepareGallery,一个是showPic,但为什么只有addLoadEvent(prepareGallery);没有addLoadEvent(showPic);呢?
另外问一下,JS的执行顺序是怎样的呢?是不是先把所有的函数加载完毕。那这样的话,没有addLoadEvent(showPic);shoePic函数里的doucument.getElementById等操作应该获取不到,为什么会正常运行呢?
如果在addLoadEvent(prepareGallery);后面加上addLoadEvent(showPic);代码依然可以正常运行,但是会显示
index.html:60 Uncaught TypeError: Cannot read property 'getAttribute' of undefined
at showPic (index.html:60)
at window.onload (index.html:48)
检查了一下也没有写错什么字母单词、标点符号,也没漏掉括号为什么会有错误
麻烦大神解释一下这三个问题(图片麻烦修改后测试)
慕勒7123956