如何在JavaScript中的输入中包含多个If语句

时间:2015-09-05 02:52:22

标签: javascript

我希望在一个输入中有多个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");
}

}

4 个答案:

答案 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>

更少的代码和清洁,希望它有所帮助