javascript - 我的代码中有哪些错误,因为它无法一键更改图像?

标签 javascript arrays button

这是我到目前为止的代码,它所能做的就是显示第一个图像,但是一旦按下按钮,图像就不会改变,我不知道该怎么办?

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/

相关文章:

javascript - 从javascript函数返回数组到objective-c xcode

javascript - 在 AngularJS 应用程序中使用 Lo-Dash 从 REST 返回总和

jquery-ui - 单击按钮时触发 jQueryUI datePicker,将结果发送到禁用的输入字段

css - 选中的按钮样式不会在 Firefox 中显示

javascript - 使用 ajax 加载选项卡内容 onclick

javascript - 在 PHP 中从 JSON_decode 数组访问值

javascript - 将带分页的 PHP 表导出为 EXCEL、PDF、PRINTABLE

javascript - 滚动时事件类未切换

python - 仅将阵列展平一层?

R-项目按钮和图形用户界面