change images on click

爱⌒轻易说出口 提交于 2020-01-15 06:29:18

问题


I found this code but I dont want to change by random. I dont know how to change images by order. Please help me!

HTML

 <div class=change><img id=bg src="items/01.jpg" alt="" /></div>

JQUERY :

var images = ["02.jpg","03.jpg","01.jpg"];

$(function() {
    $('.change').click(function(e) {
    var image = images[Math.floor(Math.random()*images.length)];
        $('#bg').parent().fadeOut(200, function() {
            $('#bg').attr('src', 'items/'+image); 
              $(this).fadeIn(200);
        });
    });
});

回答1:


You need to use index incremented by 1 instead of random. Reset index when it reaches array length.

var images = ["02.jpg","03.jpg","01.jpg"];

$(function() {
    index = 0;
    $('.change').click(function(e) {
    var image = images[index++];
    if(index == images.length) 
       index = 0;
        $('#bg').parent().fadeOut(200, function() {
            $('#bg').attr('src', 'items/'+image); 
              $(this).fadeIn(200);
        });
    });
});



回答2:


var images = ["01.jpg","02.jpg","03.jpg"];
var currentimg = 0; 

$(function() {
    $('.change').click(function(e) {

        var image = images[currentimg];
        currentimg++;
        if(currentimg > 2){
            currentimg = 0;
        }

        $('#bg').parent().fadeOut(200, function() {
            $('#bg').attr('src', 'items/'+image); 
            $(this).fadeIn(200);
      });
    });
});

Try this. This should work for you.



来源:https://stackoverflow.com/questions/14241438/change-images-on-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!