首页 > 解决方案 > jQuery:循环更改图像问题

问题描述

$(document).ready(function () {
 
    $('.box').on('click', function () {
      var images=["http://www.themadcatlady.com/wp-content/uploads/2013/11/2013-11-0212.15.22.jpg","http://tailandfur.com/wp-content/uploads/2015/05/Black-Cat-Pictures-12.jpg",
"http://tailandfur.com/wp-content/uploads/2015/05/Black-Cat-Pictures-12.jpg"];
   
          for(i=0;i<images.length;i++){
            $('#image').attr("src", images[i]);
        }
    });

});
.box {
    width: 100px;
    height: 100px;
    border: 1px solid black;
    display: inline-block;
}
 <div class="row first-row">
            <div class="box col-md-2">
                <img src="https://s-media-cache-ak0.pinimg.com/736x/fe/3c/61/fe3c61a811ad7aa24c7fcd8ff8586436--vampire-masquerade-vampire-art.jpg" class="img-fluid" id="image">
            </div>
        </div>

我有这个简单的 jQuery 代码来更改“点击”图像的来源。但是 src 只更新一次,我看不到我错过了什么......有人可以帮我吗?编码:

jQuery:

$(document).ready(function () {

    $('.box').on('click', function () {
      var images=["img-1",img-2", etc];

          for(i=0;i<images.length;i++){
            $('#image').attr("src", images[i]);
        }
    });

的HTML:

<div class="row first-row">
            <div class="box col-md-2">
                <img src="img/image.jpg" class="img-fluid" id="image">
            </div>
        </div>

标签: jqueryloops

解决方案


吸血鬼图像不是图像数组的一部分,您有 1 个图像在索引 1 和 2 处重复

以下代码循环遍历数组中的所有三个图像。将吸血鬼图像添加到图像数组中,它也将开始循环。

$(document).ready(function () {
 var currentImage = 0;
    $('.box').on('click', function () {
      var images=["http://www.themadcatlady.com/wp-content/uploads/2013/11/2013-11-0212.15.22.jpg","http://tailandfur.com/wp-content/uploads/2015/05/Black-Cat-Pictures-12.jpg",
"http://tailandfur.com/wp-content/uploads/2015/05/Black-Cat-Pictures-12.jpg"];

    console.log("currentImage", currentImage);
        if(currentImage === images.length)  currentImage = 0;
            console.log("displaying image at " + currentImage);
        $('#image').attr("src", images[currentImage]);
        currentImage = currentImage + 1;

    });
});

推荐阅读