从数组更改多个图像源

Change Multiple Image Sources from Array

我正在创建一个图片库,用户可以在其中单击 "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, '');

            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 class 的每个图像的来源。但是,它会立即用 class 替换所有图像。

好吧,您可以在这里跳过很多代码。

$(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, '');
                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.