我希望在一个输入中有多个if-else
语句,当我仅使用此代码时,how tall is the gateway arch
将获得警报,而不是how tall are the pyramids
。
这可能是有人吗?
document.getElementById("button").onclick = function() {
if (document.getElementById("ask").value == "how tall are the pyramids") {
alert("146.5 meters");
} else {
alert("How should I know");
}
}
if (document.getElementById("ask").value == "how tall is the gateway arch") {
alert("630 feet");
} else {
alert("How should I know");
}
}
答案 0 :(得分:1)
如果您愿意,可以使用尽可能多的
试试这个
var ask = document.getElementById("ask").value;
if (ask == "how tall are the pyramids") {
alert("146.5 meters");
} else if (ask == "how tall is the gateway arch") {
alert("630 feet");
} else {
alert("How should I know");
}
或者您可以使用switch..case
var ask = document.getElementById("ask").value;
switch (ask) {
case "how tall are the pyramids":
alert("146.5 meters");
break;
case "how tall is the gateway arch":
alert("630 feet")
break;
default:
alert("How should I know");
}
答案 1 :(得分:0)
只需使用if / else if / else构造。在最终(可选)其他之前,您可以拥有任意数量的其他ifs。
而不是在同一输入上多次使用getElementById()
,只需将当前值存储在变量中。
另请注意,您没有正确配对大括号。
document.getElementById("button").onclick = function() {
var question = document.getElementById("ask").value;
if (question == "how tall are the pyramids") {
alert("146.5 meters");
} else if (question == "how tall is the gateway arch") {
alert("630 feet");
} else {
alert("How should I know");
}
}
或者您可以使用switch
声明:
switch (question) {
case "how tall are the pyramids":
alert("146.5 meters");
break;
case "how tall is the gateway arch":
alert("630 feet");
break;
case "What is yellow and dangerous?":
alert("Shark infested custard");
break;
default:
alert("How should I know?");
break;
}
答案 2 :(得分:0)
你可以像这样使用switch statement:
switch(document.getElementById("ask").value) {
case "how tall are the pyramids": alert("146.5 meters"); break;
case "how tall is the gateway arch": alert("630 feet"); break;
default: alert("how should I know");
}
答案 3 :(得分:0)
最好在按钮中添加onclick事件,例如。
<button onclick="function();">Click me</button>
<强>的Javascript 强>
<script type="text/javascript">
function name(){
var data = document.getElementById("ask").value;
switch(data){
case "how tall are the pyramids": alert('msg'); break;
.
.
.
default: alert('How should I know?'); break;
}
}
</script>
更少的代码和清洁,希望它有所帮助