当我输入其名称时,我会尝试制作特定糖果的图像,但只有Ghirardelli可以使用。
<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 :(得分: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";
}
答案 1 :(得分:0)
答案 2 :(得分:0)
您的if语句并未全部到达。此问题的常见解决方案是使用else 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";
}