页面刚打开,就自动弹出了两次hello(有两张图片)
。<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>Hoverbox Image Gallery</title>
<script language="javascript">
function addImageHandlers() {
var imageElements = document.getElementsByTagName("img");
for (var i=0; i<imageElements.length; i++) {
imageElements[i].onClick = alert("hello");
}
}
</script>
</head>
<body onLoad="addImageHandlers();">
<div id="images">
<ul>
<li>
<a href="#"><img src="img/photo01.jpg" alt="description" /></a>
</li>
<li>
<a href="#"><img src="img/photo02.jpg" alt="description" /></a>
</li>
</ul>
</div>
</body></html>
。<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>Hoverbox Image Gallery</title>
<script language="javascript">
function addImageHandlers() {
var imageElements = document.getElementsByTagName("img");
for (var i=0; i<imageElements.length; i++) {
imageElements[i].onClick = alert("hello");
}
}
</script>
</head>
<body onLoad="addImageHandlers();">
<div id="images">
<ul>
<li>
<a href="#"><img src="img/photo01.jpg" alt="description" /></a>
</li>
<li>
<a href="#"><img src="img/photo02.jpg" alt="description" /></a>
</li>
</ul>
</div>
</body></html>
页面加载的时候运行了函数, 而函数并未真正赋值给onclick时间.
而是普通的弹出对话框
类似于写个aaa=add(1,2);他会执行add()函数,并把add()函数的返回值付给aaa
你的代码会执行alert(),然后将alert()函数返回值付给Onclick属性,但返回值为空。可以改成匿名函数的方式:
imageElements[i].onClick = function(){alert("hello");}