2016-11-22 82 views
2

这很简单我不确定为什么我遇到问题。我试图模仿两张图像之间的翻转卡,所以点击时,它会改变为其他图像。我在if/else语句中遇到了问题,因为每次单击图像时,它都不会将其显示到else部分。在HTML页面的源代码中,图像的src被更改,但每次都会传递if语句。使用Javascript:更改img src onclick只能使用一次

(function() { 

    // attaches event handler to image 
    window.onload = function() { 

     var image1 = document.getElementById("image1"); 
     image1.onclick = changeImage; 
    }; 

    // changes image when clicked to flip from image to text and text to image 
    function changeImage() { 
     if (document.getElementById("image1").src = "img/top.png") { 
      document.getElementById("image1").src = "img/toptext.png"; 
      //window.alert('hi'); 
     } 
     else { 
      window.alert('it passed'); 
      document.getElementById("image1").src="img/top.png"; 
     } 
    } 
})(); 
+2

检查比较运算在你的if语句,提示你使用的arent一个 –

+1

的**,如果**陈述条件是问题。将等号** = **替换为等号** == **。 – Anson

回答

7

使用==或===用于比较if条件检查。

using =将分配值并始终为真,因为分配的字符串不是空字符串。

function changeImage() { 
     if (document.getElementById("image1").src == "img/top.png") { 
      document.getElementById("image1").src = "img/toptext.png"; 
      //window.alert('hi'); 
     } 
     else { 
      window.alert('it passed'); 
      document.getElementById("image1").src="img/top.png"; 
     } 
    } 
+0

_“永远是真的。”_它只会是真的如果分配的值是truthy –

+0

@PatrickEvans是的我同意,但在这种情况下,当分配的字符串是非空字符串它将永远是真的吗? – Deep

+0

我还必须在if语句中进行比较时使用.getAttribute(“src”)。谢谢! – Alex

2

您应该使用==进行的,如果comparaison

if (document.getElementById("image1").src = "img/top.png") { 

变化成

if (document.getElementById("image1").src == "img/top.png") {