[英]Javascript/jQuery change <img src=“ ”> onclick with loop
I am creating kind of a slideshow in jQuery and on each click of the next button, I need the image src to increase. 我正在用jQuery创建一种幻灯片显示,每次单击下一步按钮时,我都需要增加图像src。 The file names of the images are 1,2,3,4,5,6,7,8,9,10,11, so I tried using a for loop.
图像的文件名是1,2,3,4,5,6,7,8,9,10,11,所以我尝试使用for循环。 But since I'm no javascript/jquery guru, I can't think of other ways to solve my issue and make it actually work.
但是由于我不是javascript / jquery专家,所以我想不出其他方法来解决问题并使其真正起作用。
With my code, nothing happens at all. 使用我的代码,什么也没有发生。
This is what I've tried: 这是我尝试过的:
$('#right_arrow').click(function()
{
for (i = 1; i <= 11; i++)
{
$('#produkti').attr('src', 'style/images/produktet/' + i + '.gif');
}
});
And this is the actual html for the image: 这是图像的实际html:
<img src="style/images/produktet/1.gif" alt="Produkti 1" id="produkti" />
you can not assign one id to same 11 images, it will never work, jquery/javascript will always pick the first element with specified id. 您不能将一个ID分配给相同的11张图像,它将永远无法工作,jquery / javascript将始终选择具有指定ID的第一个元素。
You should use class and pick image element by index. 您应该使用class并按索引选择图像元素。
$('#right_arrow').click(function()
{
for (i = 1; i <= 11; i++)
{
$('.produkti').get(i-1).attr('src', 'style/images/produktet/' + i + '.gif');
}
});
and html here: 和html在这里:
<img src="style/images/produktet/6.gif" alt="Produkti 6" class="produkti" />
The logic is - Every time you click that button, the index will return to 1. for (i = 1; i <= 11; i++)
逻辑是-每次单击该按钮,索引将返回1。for
for (i = 1; i <= 11; i++)
What you'll need to do, is have a global variable .. say var imgIndex
Then, your code should be - // somewhere ABOVE.. probably the head tag... var imgIndex = 0;
您需要做的是有一个全局变量..说
var imgIndex
然后,您的代码应该是- // somewhere ABOVE.. probably the head tag... var imgIndex = 0;
$('#right_arrow').click(function()
{
$('#produkti').attr('src', 'style/images/produktet/' + imgIndex + '.gif');
imgIndex++;
});
Keep in mind you'll have to reset this imgIndex value when it reaches max. 请记住,当此imgIndex值达到最大值时,必须将其重置。
This is a way to do this with an "auto loop" (when right arrow is clicked and current image is number 11, current image will be number 1) 这是一种通过“自动循环”执行此操作的方法(单击右箭头并且当前图像为11号时,当前图像为1号)
var current = 6;
$('#right_arrow').click(function()
{
current = (current + 1 <= 11) ? (current + 1) : (1);
$('#produkti').attr('src', 'style/images/produktet/' + current + '.gif');
});
Here's an idea with data tags. 这是一个带有数据标签的想法。
HTML: HTML:
<img src="style/images/produktet/1.gif" data-slide="1" data-max="9"/>
JS: JS:
$("#right_arrow").click(function(){
var img = $("#produkti");
var slide = img.data().slide;
var max = img.data().max;
if(slide <= max){
slide ++;
img.attr('src', 'style/images/produktet/' + slide + '.gif');
img.data().slide = slide;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.