I have this on HTML:

<script type="text/javascript" src="./scripts/changeImage.js"></script>
  <img id="myimage" onclick="changeImage()" src="./images/avatars/1.png"/>

This is the function

var cc=0;

function changeImage(){
  if(cc==-1){
      cc=0;
      document.getElementById('myimage').src="./images/avatars/1.png";
      } else if (cc==0){
      cc=1;
      document.getElementById('myimage').src="./images/avatars/2.png";
      } else if (cc==1){
      cc=2;
      document.getElementById('myimage').src="./images/avatars/3.png";
      } else if (cc==2){
      cc=0;
      document.getElementById('myimage').src="./images/avatars/4.png";
      } 
    }

I must click 2 times to change the image. I tried some tricks but nothing.

有帮助吗?

解决方案

i must click 2 times to change the image ...

At a guess, I'd say that cc starts out being -1, and so you follow this branch through your code:

cc=0;
document.getElementById('myimage').src="./images/avatars/1.png";

Since that's setting the same path that's already on the image, nothing changes. But then cc is 0, so the second click follows the next branch.


BTW, this is what switch statements are for:

function changeImage() {
    switch (cc) {
        case -1:
            document.getElementById('myimage').src = "./images/avatars/1.png";
            break;
        case 0:
            document.getElementById('myimage').src = "./images/avatars/2.png";
            break;
        case 1:
            document.getElementById('myimage').src = "./images/avatars/3.png";
            break;
        case 2:
            document.getElementById('myimage').src = "./images/avatars/4.png";
            break;
    }
    cc = cc == 2 ? 0 : cc + 1;
}

Or a map:

var imageMap = {
    -1: "./images/avatars/1.png",
    0:  "./images/avatars/2.png",
    1:  "./images/avatars/3.png",
    2:  "./images/avatars/4.png"
};
function changeImage() {

    document.getElementById('myimage').src = imageMap[cc];
    cc = cc == 2 ? 0 : cc + 1;
}

In both of the above, I've replicated the logic of your if/else series, but note that the logic of your if/else series never lets you get back to 1.png.

Also note that I'm assuming the real image paths are more complex, because otherwise you'd just want to key off the fact that you have 1.png, 2.png, etc.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top