2016-11-16 54 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"; 
}