2016-11-16 74 views
2

我正在嘗試製作特定糖果彈出的圖像,當您鍵入其名稱但只有Ghirardelli的作品。爲什麼不是這個javascript提示工作?

<p id="chocolate"></p> 
<img src="hershey.jpg" id="pic"> 
<script> 
var y = prompt("What would you like to see a picture of?"); 
if (y == "Hershey") 
{ 
    document.getElementById("chocolate").innerHTML="Hershey"; 
} 
if (y == "Reeses") 
{ 
    document.getElementById("chocolate").innerHTML="Reeses"; 
    document.getElementById("pic").src="reeses.jpg"; 
} 
if (y == "Ghiradelli") 
{ 
    document.getElementById("chocolate").innerHTML="Ghiradelli"; 
    document.getElementById("pic").src="ghiradelli.jpg"; 
} 
else 
{ 
    document.getElementById("chocolate").innerHTML="Please choose one of these three things: <ul><li>Hershey</li><li>Reeses</li><li>Ghiradelli</li></ul>"; 
    document.getElementById("pic").src="x.svg"; 
} 
</script> 
+0

如此,甚至沒有賀喜的作品? –

+0

甚至不hershey –

+1

,但它確實顯示頁面加載hershey,右 –

回答

3

這是因爲你只有一個else在整個事情。前兩個if語句獨立運作。他們工作,但最後的if是不正確的,所以else的邏輯覆蓋前兩個if所做的任何事情。

只剩下其他else if

var y = prompt("What would you like to see a picture of?"); 
if (y == "Hershey") 
{ 
    document.getElementById("chocolate").innerHTML="Hershey"; 
} 
else if (y == "Reeses") 
{ 
    document.getElementById("chocolate").innerHTML="Reeses"; 
    document.getElementById("pic").src="reeses.jpg"; 
} 
else if (y == "Ghiradelli") 
{ 
    document.getElementById("chocolate").innerHTML="Ghiradelli"; 
    document.getElementById("pic").src="ghiradelli.jpg"; 
} 
else 
{ 
    document.getElementById("chocolate").innerHTML="Please choose one of these three things: <ul><li>Hershey</li><li>Reeses</li><li>Ghiradelli</li></ul>"; 
    document.getElementById("pic").src="x.svg"; 
} 
0
  1. 使用否則,如果不是多如果。
  2. 嘗試使用回報,因爲每個if語句的最後聲明。(我不知道這點,檢查)
0

你如果不是全部被達到的語句。這個問題的一個常見解決方案是使用if語句或使用switch語句來清理代碼。此外,我試圖抽象掉不必用太多的document.getElementById聲明

<p id="chocolate"></p> 

<img src="hershey.jpg" id="pic"> 

<script> 

//sets variable y to the response in the promt 
var y = prompt("What would you like to see a picture of?"); 

//sets the chocolate paragraph variable 
var chocolate = document.getElementById("chocolate"); 

//sets the pic image variable 
var pic = document.getElementById("pic"); 

//checks for different cases of y, use switch statements when there are too  many if statements 
switch (y) { 
case "Hershey": 
    chocolate.innerHTML="Hershey"; 
    break; 
case "Reeses": 
    chocolate.innerHTML="Reeses"; 
    pic.src="reeses.jpg"; 
    break; 
case "Ghiradelli": 
    chocolate.innerHTML="Ghiradelli"; 
    pic.src="ghiradelli.jpg"; 
    break; 
default: 
    chocolate.innerHTML="Please choose one of these three things: <ul> <li>Hershey</li><li>Reeses</li><li>Ghiradelli</li></ul>"; 
    pic.src="x.svg"; 
}