0

Using Javascript, I want to toggle on and off between 2 images. So far I am using a counter and then changing my innerHTML based off if the counter is even or odd for when the image is clicked

It works the first time i click the image by replacing the image already there, but after the first time it keeps on adding images instead. How can i make it change the image after the second time rather than add images when I click?

<!DOCTYPE html>
<html>
  <head>
    <script>
      var x = 0;
      function myFunction() {
        x++;
        var div1 = document.getElementById('div1');
        if (x % 2 != 0) {
          var y = document.write('<img src="http://www.computric.com/wp-content/uploads/2011/09/119709197585381818TzeenieWheenie_Power_On_Off_Switch_red_2.svg_.med_.ng" alt="sometext" onclick=myFunction()>');
          div1.appendChild.innerHtml = y;
        } else if (x % 2 == 0) {
          var y = document.write('<img src="http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg"       alt="some_text" onclick=myFunction()>')
          div1.appendChild.innerHTML = y;
        }
      }
    </script>
  </head> 
  <body>
    <div id="div1" style="font-size:12px" onclick=myFunction()> <span onclick=myFunction()>
     <img src="http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg" alt="some_text">
     </span> 
    </div>
  </body>
</html>
4

1 回答 1

2

如果您只是想实现切换效果,这样的事情应该可以工作:

<!DOCTYPE html>
 <html>
 <head>

<script>
var x=0;
function myFunction(){
    var div1=document.getElementById('div1');
    if(x==0){
        x=1;
        document.getElementById("myimgid").src = "http://www.computric.com/wp-content/uploads/2011/09/119709197585381818TzeenieWheenie_Power_On_Off_Switch_red_2.svg_.med_.ng";
    }
    else{
        x=0;
        document.getElementById("myimgid").src = "http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg";
    }
}

</script>
 </head>
 <body>


 <div id="div1" style="font-size:12px" onclick=myFunction()>
 <span>
 <img id="myimgid" src="http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg" alt="some_text">
 </span>
 </div>

 </body>
 </html>
于 2013-04-21T22:41:21.990 回答