简体   繁体   English

使用jQuery动态更改图像源

[英]Using jQuery to change image source dynamically

I have a page that is a series of N img elements. 我的页面是一系列N img元素。 I need each image to, when clicked, change to the next image in their own series of three. 单击每个图像时,我需要将其切换为自己的三个图像系列中的下一个图像。 I have listed my html below to explain. 我在下面列出了我的html来解释。

<body>
    <div class="images">
        <div class="image_group">
            <img id="first" src="group1_image1"></img>
            <img id="second" src="group1_image2"></img> //this isn't displayed until clicked
            <img id="third" src="group1_image3"></img> //when this is displayed, it cycles back to group1image1
         </div>
         ...
         <div class="image_group">
            <img id="first" src="groupN_image1"></img>
            <img id="second" src="groupN_image2"></img>
            <img id="third" src="groupN_image3"></img>
          </div>
      </div>
</body>

Each image_group div displays only one image until clicked, when it displays the second, then the third when clicked, then cycles back to the first when clicked a third time. 每个image_group div仅显示一个图像,直到被单击为止;当它显示第二个图像时,在单击时显示第三个图像,然后在第三次单击时循环回到第一个图像。

My problem is writing a JQuery method that can do this cycling by making "second" images replace "first" images when clicked and so on. 我的问题是编写一种JQuery方法,该方法可以通过单击时将“第二”图像替换为“第一”图像来进行此循环。 The below method rewrites the image source which seems silly but I can't think of a better way to do it. 下面的方法重写了看起来很愚蠢的图像源,但是我想不出更好的方法。 I'm also not sure if the "first" class image will be isolated in the "image_group" div (as it should) or if it will change all images on the page to their "second" class image. 我也不确定“第一类”图像是否将被隔离在“ image_group” div中(是否应该),或者是否会将页面上的所有图像更改为其“第二类”图像。

$("#first").attr("src","group1_image2.jpg");

Can anyone think of a way to do this? 有人能想到一种方法吗?

I would do something like this 我会做这样的事情

$("image_group img").on("click", function() {
    var index = $(this).index();
    $(this).attr("src", index === $("img").length - 1 ? $(this).next().src : $("img")[0].src); 
});

refine your html: 优化您的html:

<body>
    <div class="images">
        <div class="image_group">
            <img id="1,1" data_num="1,1" src="group1_image1"></img>
         </div>
         ...
         <div class="image_group">
            <img id="n,1" data_num="n,1" src="groupN_image1"></img>
          </div>
      </div>
</body>

and then you might do something like: 然后您可能会执行以下操作:

$("image_group img").on("click", function() {
    var max = 3;
    var indexes = $(this).data('num').split(',');
    if ( indexes[1] == max
       indexes[1] = 1;
    else 
       indexes[1]++;
    $(this).attr("src", "group" + indexes[0] + "_image" + indexes[1]); 
    $(this).data('num', indexes.join(','))
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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