2013-12-20 52 views
0

我試圖給綠色或紅色的變量顏色值,並從那裏給imagePath一個特定的src取決於給予顏色的值。用onclick函數改變圖像的顏色不起作用?

從那裏我可以通過按任意一個按鈕在紅色和綠色之間連續切換襯衫圖像。

實際發生的是襯衫顏色變成紅色。之後,即使按下激活green()功能的綠色按鈕,它也不會變爲綠色。

My HTML code: 

<html> 
<head> 
    <script src="oands.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
    var color; 
    function red(){color = "red"; change()} 
    function green(){color = "green"; change()} 

    function change() 
    { 
     if(color = "red") 
     { 
      imagePath = 'images/red-t-shirt.png'; 
      } 
     if(color = "green") 
     { 
      imagePath = 'images/green-t-shirt.png'; 
     } 
     O("shirt").src = imagePath; 
    } 
    </script> 
    <title></title> 
</head> 

<body> 
    <div id="wrapper"> 
     <div id="content"> 
      <img id="shirt" name="shirt" src="images/white-t-shirt.png"> 
      <div class="smallbox" id="redBox" onclick="red()"> 
       red 
      </div> 

      <div class="smallbox" id="greenBox" onclick="green()"> 
       green 
      </div> 
     </div> 
    </div> 
</body> 
</html> 

oands.js代碼:

function O(obj) 
{ 
    if (typeof obj == 'object') 
    return obj; 

     else 
    return document.getElementById(obj) 
} 

回答

1

你應該這樣做:

if(color == "red") 
{ 
    imagePath = 'images/red-t-shirt.png'; 
} 
if(color == "green") 
     //^^ note the logical compare operator. Double equals 
{ 
    imagePath = 'images/green-t-shirt.png'; 
} 

而且,在這一行:

function red(){color = "red"; change();} 
     //You're missing a semicolon ^^ 

爲了更加準確,如果您知道color始終是字符串,您應該使用===。看到這個職位的更多細節:Which equals operator (== vs ===) should be used in JavaScript comparisons?

+0

謝謝!我是一個初學者。這真的幫助謝謝! – user3121403

+0

@ user3121403歡迎您:) – gideon