我必须并排显示两个数字(都以zero.gif文件开头).每个数字都需要一个输入区域供用户输入1到5之间的数字和一个显示“Process Number”的按钮,然后弹出相应的数字.
我必须为一个使用if-then-else语句,为另一个使用switch语句.我分别理解这两个,但我不知道如何在脚本代码中将两者结合起来.
目前,当我在第一个输入框中输入数字时,它们都会同时更改.如果我尝试第二个框,我会收到警告“你必须选择1到5之间的数字”.
所以我不确定如何将两者分开.我使用了不同的图像ID,但它不起作用.这是所有代码.
<script type="text/javascript"> function processNumber() { var numberInput = document.getElementById("userInput").value; // test for valid input number from 1 to 5 if (numberInput < 1 || numberInput > 5) { alert("Your number must be from 1 to 5"); return; } if (numberInput == 1) document.getElementById("ones").src="images/one.gif"; else if (numberInput == 2) document.getElementById("ones").src = "images/two.gif"; else if (numberInput == 3) document.getElementById("ones").src = "images/three.gif"; else if (numberInput == 4) document.getElementById("ones").src = "images/four.gif"; else if (numberInput == 5) document.getElementById("ones").src = "images/five.gif"; else alert("Sorry - your input is not recognized"); // likely a non numeric was entered if we got here switch (numberInput) { case "1": document.getElementById("group").src = "images/one.gif"; break; case "2": document.getElementById("group").src = "images/two.gif"; break; case "3": document.getElementById("group").src = "images/three.gif"; break; case "4": document.getElementById("group").src = "images/four.gif"; break; case "5": document.getElementById("group").src = "images/five.gif"; break; default: alert("Sorry - your input is not recognized"); // default in case a non numeric was entered } // end switch (numberInput) } // end function processNumber() </script>
解决方法
一个简单的解决方案可以是一个字符串数组:
var numbers = ["zero","one","two","three","four","five"]; if (numbers[numberInput] != undefined) { document.getElementById("ones").src = "images/" + numbers[numberInput] + ".gif"; document.getElementById("group").src = "images/" + numbers[numberInput] + ".gif"; } else alert("Sorry - your input is not recognized");
我想保持清洁,但这只是其中一个解决方案.如果你经常使用它,你可以发挥作用.