从阵列更改多个图像源

时间:2015-07-08 18:18:32

标签: javascript jquery arrays gallery

我正在创建一个图片库,用户可以点击" next"并且图像将随下一个图像一起更新。所有图像都应更新为不同于当前显示的图像。

例如,点击下一个按钮后:

  
      
  • Image01 - > Image04
  •   
  • Image02 - > Image05
  •   
  • Image03 - > Image06
  •   

JSFiddle

HTML:

 <div class="socialItem">
     <img class="socialImage" src="http://placehold.it/240.jpg" width="290" height="250" alt="" />
 </div>
 <div class="socialItem">
     <img class="socialImage" src="http://placehold.it/250.jpg" width="290" height="250" alt="" />
 </div>
 <div class="socialItem">
     <img class="socialImage" src="http://placehold.it/260.jpg" width="290" height="250" alt="" />
 </div>
 <a id="swapnextimg">Next</a>

JQuery的:

$(function() {

    var images = ['240', '250', '260', '123', '200'];
    var max = images.length;
    $('#swapnextimg').click( function() {
        $(".socialImage").each(function(index) {
            console.log( index + ": " + $( this ).attr('src') );
            // Get current image src
            var curSrc = $(this).attr('src');

            // Find ID in image src
            var curID = curSrc.replace(/.*\/(.*?)\.jpg/i, '$1');

            var curIdx = 0;

            // Search image list for index of current ID
            while (curIdx < max) {
                if (images[curIdx] == curID) {
                    break;
                }
                curIdx++;
            }

            // For convenience
            var imgSrcBase = 'http://placehold.it/';

            // Next image on button (and image) click

            curIdx = (curIdx+1) % max;
            $(this).attr('src', imgSrcBase+images[curIdx]+'.jpg');
        });
    });
});

This code is adapted partially from this answer.

我正在尝试使用.each逐步替换具有socialImage类的每个图像的来源。但是,它会立即用该类替换所有图像。

1 个答案:

答案 0 :(得分:1)

嗯,你可以在这里跳过很多代码。

$(function() {

    var images = ['240', '250', '260', '123', '200'];
    var max = images.length;
    var curIdx = -1;
    $('#swapnextimg').click( function() {
        $(".socialImage").each(function(index) {
            if(curIdx === -1) {
                var curId = $(this).attr('src').replace(/.*\/(.*?)\.jpg/i, '$1');
                curIdx = images.indexOf(curId);
            }

            // For convenience
            var imgSrcBase = 'http://placehold.it/';

            // Next image on button (and image) click

            curIdx = (curIdx+1) % max;
            $(this).attr('src', imgSrcBase+images[curIdx]+'.jpg');
        });
    });
});

在第一次单击时,您将查找第一个图像的索引。 之后,您只需将索引递增1。