【发布时间】:2019-04-15 00:31:16
【问题描述】:
假设数组的长度为 1000。我正在尝试创建一种简单的方法来遍历存储在数组中的图像路径而不会越界。下面的方法在单击“下一步”按钮以增加数组索引时使用模数很好地处理环绕,但当我必须从索引中减少和减去一个时(当用户单击上一个按钮时)。
基本上我想做的是:
998 -> click next -> 999
999 -> click next -> 0
0 -> click previous -> 999
我的 Javacript
var index = 0;
$('.catalog-img-container').attr("src", javascript_array[index]);
$(".next").click(function(){
$('.catalog-img-container').attr("src", javascript_array[++index%arrayLength]);
});
$(".previous").click(function(){
$('.catalog-img-container').attr("src", javascript_array[--index]);
alert(index);
感谢任何帮助
非常感谢。
【问题讨论】:
-
--index%arrayLength应该可以正常工作。 -
试过了,不行。
-
@Shmiddty 应该,但没有。
-
哦,我明白了,问题是索引小于0的时候。
-
你试过 if/else 语句吗?
标签: javascript jquery