简体   繁体   中英

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. 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. But since I'm no javascript/jquery guru, I can't think of other ways to solve my issue and make it actually work.

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:

<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.

You should use class and pick image element by index.

$('#right_arrow').click(function()
{
    for (i = 1; i <= 11; i++)
    {
        $('.produkti').get(i-1).attr('src', 'style/images/produktet/' + i + '.gif');
    }
});

and html here:

<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++)

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;

$('#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.

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)

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:

<img src="style/images/produktet/1.gif" data-slide="1" data-max="9"/>

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;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM