2016-11-22 110 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") {