如何使用上一个/下一个功能循环数组中的图像

How to loop images in array with prev/next functionality

本文关键字:数组 图像 循环 功能 何使用 上一个 下一个      更新时间:2024-01-18

我有一个JS数组imgs[]

该阵列包含如下图像路径:["img/image1.png", "img/image2.png"]

我有两个功能:

function prev() {
    $('#project-image').html("<img src='"+imgs[0]+"' alt='Projekt'/>")
}
function next() {
    $('#project-image').html("<img src='"+imgs[1]+"' alt='Projekt'/>")
}

它们在HTML中被调用如下:

<nav id="pagination">
  <a id="prev" href="javascript:prev();"></a>
  <a id="next" href="javascript:next();"></a>
</nav>

然而,我遇到的问题是,现在它们被设置为数组中的固定键(由我硬编码),如imgs[1]

如何使用这两个函数动态循环数组中的所有图像?

单击"下一个"链接时,我想加载阵列中的下一个图像。当点击"prev"链接时,我想加载上一个图像。我的数组主要由两个以上的图像组成,而且它们并不像上面的例子那样全部命名。因此,图像的名称各不相同。

有什么办法吗?

jsBin演示

var images = [
  "img/image1.jpg",
  "img/image2.jpg",
  "img/image3.jpg"
];
// ======================================
var tot = images.length;
var c = 0; // current image (array key index)
function loadImage(){
  $("<img/>").attr("src",images[c]).load(function() {
      $('#gallery').html( this );
  }); 
}
loadImage(); // load 1 image
$('#prev, #next').click(function(){
  id= this.id==='next' ? c++ : c-- ;
  c= c==-1 ? tot-1 : c%tot ;
  loadImage(); 
});

虽然代码非常不言自明
id= this.id==='next' ? c++ : c-- ;将确定单击按钮的ID并增加或减少获得精确数组密钥所需的CCD_ 6值。

为了循环数组键,使用这个三元运算符";技巧":c= c==-1 ? tot-1 : c%tot ;,其中c是当前密钥索引,tot是数组密钥的总数。

这应该会给你一个良好的开端。用";正在加载图像"info,我把它留给你!:)快乐编码

我刚刚为它写了一个方便的对象

游标对象

$.cursor = function(options)​ {
  var cursor = this;
  var array = options.array;
  var idx = options.position || 0;
  cursor.prev = function() {
    if(idx > 0) {
      return array[--idx];
    }
    return null;
  };
  cursor.current = function() {
    if(idx < array.length) {
      return array[idx];
    }
    return null;
  };
  cursor.next = function() {
    if(idx + 1 < array.length) {
      return array[++idx];
    }
    return null;
  };
  return cursor;
};

示例

var cursor = $.cursor({ array: [1,2,3,4,5] });
$("#prev").click(function(){
  if(cursor.prev() !== null) {
    $("#cur").html(cursor.current());
  }
});
$("#next").click(function(){
  if(cursor.next() !== null) {
    $("#cur").html(cursor.current());
  }
});
$("#cur").html(cursor.current());

首先找到数组的偏移量是图像链接所在的位置,然后对于next()转到下一个偏移量,如果达到最后一个偏移,则显示0(零)偏移量,依此类推。对于prev()转到当前图像偏移量,偏移量-1将为上一个图像,如果达到偏移量0(零。

简单,只需将当前图像密钥存储在变量中

current_image = 0;
function prev() {
    current_image--;
    $('#project-image').html("<img src='"+imgs[current_image]+"' alt='Projekt'/>")
}
function next() {
    current_image++;
    $('#project-image').html("<img src='"+imgs[current_image]+"' alt='Projekt'/>")
}

我想您忘记创建var索引了;在您的函数之外并动态使用它。然后,您可以使用index++或index-将偏移量更改一,而不是对值进行"硬编码"。稍后,您甚至可以使用if来检查当前索引,并改进代码以在显示(例如)数组的最后一个img时执行您想要的操作。希望它能有所帮助!