gpt4 book ai didi

javascript - 尝试在 JavaScript 中使用数组更改图像

转载 作者:行者123 更新时间:2023-12-03 07:28:12 24 4
gpt4 key购买 nike

<!DOCTYPE html> 
<html>
<body>
<img id="myImage" src="Red.jpg" width="209" height="241">
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
<script>
index=(0)
var traffic = ["Red","Rambo","Green","Yellow"]
function changeImage() {
var image = document.getElementById('Light');
if traffic[index] === "Red" {
image.src = "Rambo.jpg";
index= (index+1)
} else if traffic[index] === "Rambo" {
image.src = "Green.jpg";
index= (index+1)
} else if traffic[index] === "Green" {
image.src = "Yellow.jpg";
index= (index+1)
} else {
image.src = "Red.jpg";
index=0
}
}
</script>
</html>
</body>

这是我的代码,我不明白为什么当我单击按钮时图像不会改变图像是所有 .jpg 文件都包含在同一个文件夹中并且大小相同任何想法为什么不会更改图像,我目前猜测这与===有关,或者我使用单词而不是数字来表示它们

最佳答案

这里有很多问题:

  1. if 语句两边有括号
  2. 关闭 html 标签后关闭 body 标签
  3. document.getElementById 未获取与 img id 相同的 id

所以,这可行,但也许首先检查 javascript 和 HTML 语法可能是一个好的开始:

<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Red.jpg" width="209" height="241">
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
<script>
var index = 0;
var traffic = ["Red","Rambo","Green","Yellow"];
var image = document.getElementById('myImage');

function changeImage() {
if (traffic[index] === "Red") {
image.src = "Rambo.jpg";
index++;
} else if (traffic[index] === "Rambo") {
image.src = "Green.jpg";
index++;
} else if (traffic[index] === "Green") {
image.src = "Yellow.jpg";
index++;
} else {
image.src = "Red.jpg";
index = 0;
}
}
</script>

</body>
</html>

关于javascript - 尝试在 JavaScript 中使用数组更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35918424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com