首页 > 解决方案 > 按钮按下时图像更改损坏

问题描述

当我单击一个按钮时,我试图让一整页的图像发生变化。这是我当前的代码。我现在的问题是我可以很好地更改一个图像,但是当我添加代码来更改第二个图像时,它会阻止第一个图像发生变化,也不会让第二个图像变回其原始图像。

这是我的 JavaScript

    //First image
var imageSources = ["origonal-image.jpg","2ndimage.jpg"]
    var buttons = document.getElementsByClassName("change-image")[0];
    var index = 0;

      buttons.addEventListener('click', function() {
        if (index === imageSources.length) {
          index = 0;
        }
            
        document.getElementById("imagechangingid").src = imageSources[index];
        index++;
    });

    //Second image
var imageSources1 = ["origonal-image.jpg","2ndimage.jpg"]
    var buttons = document.getElementsByClassName("change-image")[0];
    var index = 0;
    
    buttons.addEventListener('click', function() {
      if (index === imageSources1.length) {
        index = 0;
      }
         
     document.getElementById("imagechangingid2").src = imageSources1[index];
     index++;
 });

标签: javascript

解决方案


这是因为当您编写以下代码两次时,您将覆盖您的第一个事件侦听器。一个实现(我猜是第二个)将覆盖另一个

buttons.addEventListener('click', function() {}

如果同一个按钮点击应该改变两个图像 - 你应该在同一个事件处理程序中处理它。

    var imageSources = ["origonal-image.jpg","2ndimage.jpg"]
    var buttons = document.getElementsByClassName("change-image")[0];
    var imageSources1 = ["origonal-image.jpg","2ndimage.jpg"]
    var buttons = document.getElementsByClassName("change-image")[0];
    var index = 0;
    var indexOne = 0;
    
    buttons.addEventListener('click', function() {
      if (index === imageSources1.length) {
        index = 0;
      }
         
       document.getElementById("imagechangingid2").src = imageSources1[index];
       index++;
       if (indexOne === imageSources.length) {
          indexOne = 0;
        }
            
        document.getElementById("imagechangingid").src = imageSources[indexOne];
        indexOne++;
 });

推荐阅读