2016-01-17 66 views
0

我试图通过单击切换这些图片。 JavaScript直接来自mozilla教程,所以我不确定它为什么不起作用,什么都没有发生。我正在开发cloud9。使用javascript切换图像

我的HTML:

<img id="swagBunny" src="images/large.jpg" height="150" width="186" alt="Swaggy Bunny"/> 

我的Java脚本:

var myImage = document.querySelector('img'); 

$(function(){ 
    myImage.onclick = function() { 
     var mySrc = myImage.getAttribute('src'); 
     if(mySrc === 'images/large.jpg') { 
      myImage.setAttribute ('src','images/images.jpg'); 
     } else { 
      myImage.setAttribute ('src','images/large.jpg'); 
     } 
    }; 
}); 
+0

你应该HTML也是JavaScript的!请改为提供相应的HTML。 – hotzst

回答

0

不明白为什么它不工作。这里是你的JavaScript的一个工作示例:

$(function(){ 
 
    var myImage = document.querySelector('img'); 
 
    myImage.onclick = function() { 
 
     var mySrc = myImage.getAttribute('src'); 
 
     if(mySrc === 'http://static.tumblr.com/1bd1b615e6da70dd71dc84fd2f47c80d/zpmncfu/oxNng9hfv/tumblr_static_95p88l86si88ks4w4wws04wk8.png') { 
 
      myImage.setAttribute ('src','https://cdn-insomniac.s3.amazonaws.com/emoji_sexface.png'); 
 
     } else { 
 
      myImage.setAttribute ('src','http://static.tumblr.com/1bd1b615e6da70dd71dc84fd2f47c80d/zpmncfu/oxNng9hfv/tumblr_static_95p88l86si88ks4w4wws04wk8.png'); 
 
     } 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img src="http://static.tumblr.com/1bd1b615e6da70dd71dc84fd2f47c80d/zpmncfu/oxNng9hfv/tumblr_static_95p88l86si88ks4w4wws04wk8.png" alt="Smiley face" height="42" width="42">

+0

是否因为我的变量myImage是在函数之外定义的? – CubeOfCheese

+0

我不认为这是一个问题。你在控制台看到什么错误?你包括jQuery? – jianweichuah

+0

我相信这只是Cloud9的小故障,因为它现在完美运行,感谢您的帮助 – CubeOfCheese