当我在我的网站上运行代码时,它开始使用图像jackhammers1而不是jackhammers0,并且不会执行startBouncing()方法。它只显示带有一个图像而没有动画的表单。这是从教科书中复制的一个例子,所以我看不出它应该如何工作。
<!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=iso-8859-1" />
<title>JackHammer</title>
<script type="text/javascript">
/* <![CDATA[ */
var jackhammers = newArray(11);
var curJackhammer = 0;
var direction;
var begin;
jackhammers[0] = "jackhammer0.gif";
jackhammers[1] = "jackhammer1.gif";
jackhammers[2] = "jackhammer2.gif";
jackhammers[3] = "jackhammer3.gif";
jackhammers[4] = "jackhammer4.gif";
jackhammers[5] = "jackhammer5.gif";
jackhammers[6] = "jackhammer6.gif";
jackhammers[7] = "jackhammer7.gif";
jackhammers[8] = "jackhammer8.gif";
jackhammers[9] = "jackhammer9.gif";
jackhammers[10] = "jackhammer10.gif";
function bounce(){
if(curJackhammer == 10)
curJackhammer = 0;
else
++curJackhammer;
document.getElementsByTagName("img")[0].src = jackhammers[curJackhammer].src;
if(curJackhammer == 0)
direction = "up";
else if(curJackhammer == 10)
direction = "down";
document.getElementsByTagName("img")[0].src = jackhammers[curJackhammer];
}
function startBouncing(){
if (begin)
clearInterval (begin);
begin = setInterval("bounce()",90);
}
/* ]]> */
</script>
</head>
<body>
<h1>Jackhammer Man</h1>
<p><img src="jackhammer1.gif" height="113" width="100" alt="Image of a man with a jackhammer." /></p>
<form action="" enctype="text/plain">
<p>
<input type="button" value="Start Bouncing" onclick="startBouncing();" />
<input type="button" value="Stop Bouncing" onclick="clearInterval(begin);" />
</p>
</form>
</body>
</html>
答案 0 :(得分:0)
它以jackhammer1开头,因为在html源代码中你有<img src="jackhammer1.gif"...
而不是jackhammer0,而也是当用户点击按钮开始弹跳时,它将以jackhammer1开头,因为在javascript你在交换图像之前将curJackhammer
从0增加到1 。
我认为以下代码会执行您想要的操作...(不知道您尝试使用direction = "up" / "down"
做了什么)。
请注意,javascript中if
和else
之后通常需要花括号,但如果只有一个命令,则它们是可选的。
<!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=iso-8859-1" />
<title>JackHammer</title>
<script type="text/javascript">
var curJackhammer = 0;
var begin;
function bounce() {
document.getElementsByTagName('img')[0].src =
'jackhammer' + curJackhammer + '.gif';
curJackhammer ++;
if (curJackhammer > 10) {
curJackhammer = 0;
}
}
function startBouncing(){
if (begin) {
clearInterval (begin);
}
begin = setInterval(bounce,90);
}
</script>
</head>
<body>
<h1>Jackhammer Man</h1>
<p><img src="jackhammer1.gif" height="113" width="100"
alt="Image of a man with a jackhammer." /></p>
<form action="" enctype="text/plain">
<p>
<input type="button" value="Start Bouncing" onclick="startBouncing();" />
<input type="button" value="Stop Bouncing" onclick="clearInterval(begin);" />
</p>
</form>
</body>
</html>