简体   繁体   English

如何使用OnClick更改图像?

[英]How do I change images using OnClick?

I have 7 images, it starts in 0 and I want to change them one by one each time I click on the image. 我有7张图片,它从0开始,每次单击图片时,我都希望一张一张地更改它们。

This is what I have so far: 这是我到目前为止的内容:

function changePic() {
    var img = new Array("1.png", "2.png", "3.png", "4.png", "5.png", "6.png");
        for(var p=0; p<6; p++) {
            document.getElementById("image").src=img[p]; 
        }                   
}

HTML: img onclick="changePic()" src="0.png" id="image"/ HTML:img onclick =“ changePic()” src =“ 0.png” id =“ image” /

The problem is that it changes everything at once, so it skips from img 0 to 6. 问题在于它会立即更改所有内容,因此它会从img 0跳到6。

You're setting the src 6 times with each click. 您每次点击都会设置src 6次。 You want to do it once, and increment a counter outside the function: 您只需执行一次,然后在函数外增加一个计数器:

var imgs = new Array("1.png", "2.png", "3.png", "4.png", "5.png", "6.png");
var index = 0;
function changePic() {
    document.getElementById('image').src = imgs[index];
    index++;
    if ( index >= imgs.length ) index = 0;
}

You may want a closure, to reduce global namespace goop. 您可能需要关闭,以减少全局名称空间的混乱。 Just be careful to define it before your HTML <img> : 只需在HTML <img>之前定义它即可:

var changePic = (function(imgs) {
    var index = 0;
    return function changePic() {
        document.getElementById('image').src = imgs[index++];
        if ( index >= imgs.length ) index = 0;
    }
})(["1.png", "2.png", "3.png", "4.png", "5.png", "6.png"]);

get rid of the loop, and do something like this.. 摆脱循环,做这样的事情。

   var currentPic=0;
   function changePic() {
        var img = new Array("1.png", "2.png", "3.png", "4.png", "5.png", "6.png");                           
           document.getElementById("image").src=img[currentPic]; 
           currentPic++;   
           if(currentPic > 5) {currentPic=0;}              
    }

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

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