这是我到目前为止的代码,它所能做的就是显示第一个图像,但是一旦按下按钮,图像就不会改变,我不知道该怎么办?
var index = 0;
var ImageList = ["Images\sad.png", "Images\happy.png"];
function changeImage() {
index = index + 1;
if (index == ImageList.length) {
index = 0;
'at this point it is supposed to change the image'
}
var image1 = document.getElementById("myImage");
image1.src = ImageList[index];
}
<button onclick="changeImage()">Change emotions</button>
<img id="myImage" src="Images\happy.png" style="width:200px">
最佳答案
您应该设置一个包含元素引用的全局变量,而不是在每次函数调用时都设置它。
另一件事 - 您的 index
最初设置为 0
并且默认的 img
是数组中第二个位置的图像,带有索引1
,因此第一个函数调用没有发生任何事情,因为 src
没有更改。
var index = 0;
var ImageList = ["http://placehold.it/350x150", "http://placehold.it/150x150"];
var image1 = document.getElementById("myImage");
function changeImage() {
image1.src = ImageList[index];
if (index < ImageList.length-1) {
index = index + 1;
} else {
index = 0;
}
}
<img id="myImage" src="http://placehold.it/150x150" style="width:200px">
<button onclick="changeImage()">Change emotions</button>
关于javascript - 我的代码中有哪些错误,因为它无法一键更改图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42424894/