简体   繁体   English

图片交换点击jQuery,3张图片

[英]image swap click jquery, 3 images

I want to be able to get the original image and cycle through 2 more images back to it so far I have this, but I dont know how to add an extra image 我想要能够获得原始图像并循环显示另外2张图像,到目前为止,我已经拥有了,但是我不知道如何添加额外的图像

  $('img').on({'click': function() {
    var src = ($(this).attr('src') === '1.png') // current image
        ? '2.png' 
       : '1.png';
   $(this).attr('src', src);

}});

One easy solution is to use an array with a counter variable and then loop over it in the click handler like 一种简单的解决方案是使用带有计数器变量的数组,然后像在点击处理程序中那样在其上循环

 var images = ['//placehold.it/64/ff0000?text=1.png', '//placehold.it/64/00ff00?text=2.png', '//placehold.it/64/0000ff?text=3.png'], counter = 0; $('img').on({ 'click': function() { counter = ++counter >= images.length ? 0 : counter; $(this).attr('src', images[counter]); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img src="//placehold.it/64/ff0000?text=1.png" /> 

To avoid polluting global namespace I would use a closure as below. 为了避免污染全局名称空间,我将使用如下所示的闭包。 Check fiddle - Fiddle . 检查小提琴- 小提琴

$('img').on('click', (function() {
    var arr = [ ... paths to your images];
    return function() {
        var current = arr.indexOf( this.src );
        current--;
        this.src = current > 0 ? arr[ current ] : arr[0];
   }
})() );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM