我在JavaScript中工作,我需要创建一个交通灯,每次点击按钮时都会改变颜色。我花了很长时间在它上面,我仍然无法使它工作。有人可以帮我看看,并给我一些如何让它工作的提示。
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Light1.gif" width="500" height ="350">
<p>
<button onclick="myFunction()">Change Light</button>
<p>
<p>Click Change Light to change the traffic light.</p>
<script>
var image = document.getElementById('myImage');
var p1 = new Image();
p1.src = "Light1.gif";
var p2= new Image();
p2.src = "Light2.gif";
var p3 = new Image();
p3.src = "Light3.gif";
var p4 = new Image();
p4.src = "Light4.gif";
var imgArray = [p1,p2,p3,p4];
var n = 0;
function myFunction(){
n = n + 1;
if (n === imgArray.length) {
n = 0
}
image.src = imgArray[n];
}
</script>
</body>
</html>
答案 0 :(得分:2)
首先,您的代码中存在语法错误,您需要在发布之前进行检查。大多数行都缺少行终止符;
,并且还有额外的大括号。
对于此问题,您正在创建Image类型的对象,然后将其作为源映射到原始图像元素,这将无效。您可以创建文本值数组(图像名称),如下所述。
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Light1.gif" width="500" height="350">
<p>
<button onclick="myFunction()">Change Light</button>
<p>
<p>Click Change Light to change the traffic light.</p>
<script>
var image = document.getElementById('myImage');
var p1 = "Light1.gif";
var p2 = "Light2.gif";
var p3 = "Light3.gif";
var p4 = "Light4.gif";
var imgArray = [p1, p2, p3, p4];
var n = 0;
function myFunction() {
n = n + 1;
if (n == imgArray.length) {
n = 0
};
image.src = imgArray[n];
}
</script>
</body>
</html>
&#13;
专业提示:缩进代码以提高可读性
答案 1 :(得分:1)
如果我理解正确,我认为您正在尝试做以下事情:
代码中的更正:
<script type="text/javascript">
function grid_SelectionChanged(s,e) {
s.GetSelectedFieldValues("ContactName",GetSelectedFieldValuesCallback);
}
function GetSelectedFieldValuesCallback(values) {
selList.BeginUpdate();
try {
selList.ClearItems();
for(var i=0;i<values.length;i++) {
selList.AddItem(values[i]);
}
} finally {
selList.EndUpdate();
}
document.getElementById("selCount").innerHTML=grid.GetSelectedRowCount();
}
</script>
}
image.src = imgArray [n] .src;
.src
var image = document.getElementById('myImage');
var p1 = new Image()
p1.src = "Light1.gif"
var p2= new Image()
p2.src = "Light2.gif"
var p3 = new Image()
p3.src = "Light3.gif"
var p4 = new Image()
p4.src = "Light4.gif"
var imgArray = [p1,p2,p3,p4];
var n = 0;
function myFunction(){
n = n + 1;
if(n == imgArray.length){
n = 0};
image.src = imgArray[n].src;
}
答案 2 :(得分:1)
Spidey说,你正在将图像对象映射到另一个图像的src。
您也可以用以下内容替换循环内的行:
image.src = imageArray [n] .src;
答案 3 :(得分:0)
问题在于
var p1 = new Image()
p1.src = "Light1.gif"
您需要的只是
var p1 = "Light1.gif"
请参阅我的CodePen。
确保在行尾记住你的分号