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

时间:2012-07-21 18:21:15

标签: javascript jquery arrays loops

我有一个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]

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

单击“下一步”链接时,我想加载数组中的下一个图像。单击“上一步”链接时,我想加载上一张图像。我的数组主要包含两个以上的图像,而且它们并不像上面的例子那样被命名。所以图像的名称各不相同。

任何想法如何做到这一点?

5 个答案:

答案 0 :(得分:1)

我刚为它写了a handy object

光标对象

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

答案 1 :(得分:1)

jsBin demo

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 并且增加或减少获得精确数组键所需的c值。

要循环数组键,请使用此三元运算符“技巧”:c= c==-1 ? tot-1 : c%tot ;其中c是当前键索引,tot是总数数组键。

这应该会给你一个良好的开端。要通过“加载图片...”信息招待您的访问者,我会留给您! :)快乐的编码

答案 2 :(得分:0)

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

答案 3 :(得分:0)

简单,只需将当前图像键存储在var。

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'/>")
}

答案 4 :(得分:0)

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