我有这个jQuery代码来旋转存储在数组中的图像:
index = 0;
$('.thumbnail').click(function(){
$('.large_view').show();
$('.large_view').prepend('<img src="'+images[index]+'" width="450px"/>');
});
$('.next').click(function(){
index = (index==images.length-1)?0:(index+1);
$('.large_view img').attr('src',images[index]);
});
$('.previous').click(function(){
index = (index===0)?(images.length-1):(index-1);
$('.large_view img').attr('src',images[index]);
});
但问题在于,由于index = 0;
,相同的图像始终显示,而不是已点击的图像。我需要修复问题,但在点击.previous
和.next
时,仍然可以以某种方式显示数组中的上一个/下一个项目。
应该怎么做?
答案 0 :(得分:0)
您可以使用一个小帮手Javascript函数来找出“下一个”和“上一个”。查看下面定义的previousIndex和nextIndex方法。我使用了我能想象到的最简单的HTML。
我还注意到你没有将large_image的源代码设置为任何东西(在我们看到的代码中)所以我添加了将图像初始化为列表中的第一个图像的行。试试这个,看看这是否是您正在寻找的行为。
var index = 0;
var images = [
'http://placehold.it/300&text=first+picture',
'http://placehold.it/300&text=second+picture',
'http://placehold.it/300&text=third+picture'
];
var previousIndex = function(index, length) {
if (index <= 0) {
return length - 1; // cycle backwards to the last image
} else {
return index - 1;
}
}
var nextIndex = function(index, length) {
return ((index + 1) % length)
};
$('.next').click(function() {
index = nextIndex(index, images.length);
$('.large_view img').attr('src', images[index]);
});
$('.previous').click(function() {
index = previousIndex(index, images.length);
$('.large_view img').attr('src', images[index]);
});
/** initialize the image on load to the first one */
$('.large_view img').attr('src', images[index])
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='next'>next</a>
<a href='#' class='previous'>prev</a>
<div class="large_view">
<img />
</div>