jquery - jQuery:循环更改图像问题
问题描述
$(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>
解决方案
吸血鬼图像不是图像数组的一部分,您有 1 个图像在索引 1 和 2 处重复
以下代码循环遍历数组中的所有三个图像。将吸血鬼图像添加到图像数组中,它也将开始循环。
$(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;
});
});
推荐阅读
- r - 在 mutate 中添加变量标签
- python - 如何使用基于函数内用户输入的方法更改类
- powershell - 使用 csv 脚本 PowerShell 更新 SQL Server
- c# - 如何在实体框架中启用身份?
- reactjs - React Navigation Drawer Navigator 覆盖 onBackdropPress 或 onClose 监听器?
- php - 无法将所有 WP-QUERY 结果加载到自定义循环中的 JSON 编码
- mongodb - 如何在 MongoDB 中使用 LIKE 编写查询?
- ruby-on-rails - RAILS_ENV、NODE_ENV 独立 Docker 镜像
- php - 多对多关系的 Laravel 查询构建器
- visual-studio - 当变更集标记为已解决时,Visual Studio 更改卡在 VSTS 中设置的状态