更改多个图像

时间:2016-01-22 14:54:49

标签: javascript image

我最近遇到过一段我一直在研究的代码问题。我被要求创建一个数组,并通过一个按钮循环通过红绿灯,这就是我所做的:

<!DOCTYPE html>
<html>


<head>
<title> Traffic Lights </title>
</head>

<body>

<script>
whatPosition=1;
var images=["redlight.gif","redandamber.gif","greenlight.gif","amberlight.gif"];
function changeImage() {

if (whatPosition==0) {
document.getElementById("image").innerHTML=images[1];
whatPosition=1;

} 

else if (whatPosition==1){
document.getElementById("image").innerHTML=images[2]
whatPosition=2;
alert("I am an alert box!");
}
else if (whatPosition==2){
document.getElementById("image").innerHTML=images[3]
whatPosition=3;
}
else if (whatPosition==3){
document.getElementById("image").innerHTML=images[4]
whatPosition=4;
}
else if (whatPosition==4){
document.getElementById("image").innerHTML=images[0]
whatPosition=0;

2 个答案:

答案 0 :(得分:0)

您需要设置src属性。

<img src="" />
<!---^^^^^^---- You need to set this to make this work.

替换所有:

document.getElementById("image").innerHTML=images[0];

使用以下格式

document.getElementById("image").src = images[0]);

答案 1 :(得分:0)

图片没有innerHTML,试试这个:

document.getElementById("image").src = images[0];