$(document).ready(function () {
$('.box').on('click', function () {
var images=["http://www.themadcatlady.com/wp-content/uploads/2013/11/2013-11-0212.15.22.jpg","http://tailandfur.com/wp-content/uploads/2015/05/Black-Cat-Pictures-12.jpg",
"http://tailandfur.com/wp-content/uploads/2015/05/Black-Cat-Pictures-12.jpg"];
for(i=0;i<images.length;i++){
$('#image').attr("src", images[i]);
}
});
});
.box {
width: 100px;
height: 100px;
border: 1px solid black;
display: inline-block;
}
<div class="row first-row">
<div class="box col-md-2">
<img src="https://s-media-cache-ak0.pinimg.com/736x/fe/3c/61/fe3c61a811ad7aa24c7fcd8ff8586436--vampire-masquerade-vampire-art.jpg" class="img-fluid" id="image">
</div>
</div>
我有这个简单的jQuery代码,可以在“点击”时更改图片的来源。但是src仅更新一次,我看不到丢失的内容...有人可以帮帮我吗?代码:
jQuery:
$(document).ready(function () {
$('.box').on('click', function () {
var images=["img-1",img-2", etc];
for(i=0;i<images.length;i++){
$('#image').attr("src", images[i]);
}
});
HTML:
<div class="row first-row">
<div class="box col-md-2">
<img src="img/image.jpg" class="img-fluid" id="image">
</div>
</div>
答案 0 :(得分:2)
吸血鬼图像不是图像数组的一部分,并且您有1个图像在索引1和2处重复
以下代码循环遍历数组中的所有三个图像。将吸血鬼图像添加到images数组中,它也会开始循环播放。
$(document).ready(function () {
var currentImage = 0;
$('.box').on('click', function () {
var images=["http://www.themadcatlady.com/wp-content/uploads/2013/11/2013-11-0212.15.22.jpg","http://tailandfur.com/wp-content/uploads/2015/05/Black-Cat-Pictures-12.jpg",
"http://tailandfur.com/wp-content/uploads/2015/05/Black-Cat-Pictures-12.jpg"];
console.log("currentImage", currentImage);
if(currentImage === images.length) currentImage = 0;
console.log("displaying image at " + currentImage);
$('#image').attr("src", images[currentImage]);
currentImage = currentImage + 1;
});
});
答案 1 :(得分:1)
首先,吸血鬼图像不在图像数组中。其次,为什么不遍历整个数组,为什么不在数组中找到当前源的索引,然后将src属性更改为下一个数组,当到达末尾时,将当前索引设置为- 1。 这是它的代码。
$(function(){
var images=["http://www.themadcatlady.com/wp-content/uploads/2013/11/2013-11-0212.15.22.jpg","http://tailandfur.com/wp-content/uploads/2015/05/Black-Cat-Pictures-12.jpg",
"http://tailandfur.com/wp-content/uploads/2015/05/Black-Cat-Pictures-12.jpg"];
$('.box').on('click', function () {
var currentIndex = images.indexOf($("#image").attr("src"));
if(currentIndex === images.length - 2){
currentIndex = -1;
}
$("#image").attr("src", images[currentIndex+1]);
});
});
答案 2 :(得分:0)
如前所述,您不能在数组上循环,必须在每次单击时递增。
$(document).ready(function () {
var images = new Array();
images[0] = "http://www.themadcatlady.com/wp-content/uploads/2013/11/2013-11-0212.15.22.jpg"
images[1] = "http://tailandfur.com/wp-content/uploads/2015/05/Black-Cat-Pictures-12.jpg"
images[2] = "http://tailandfur.com/wp-content/uploads/2015/05/Black-Cat-Pictures-12.jpg"
var i = 0;
$('.box').on('click', function () {
$('#image').attr('src', images[i]);
i++;
});