2015-09-05 146 views
1

我希望在一个输入中有多个if-else语句,当我使用此代码时,只有how tall is the gateway arch会得到警报而不是how tall are the pyramids如何有一个以上的语句在JavaScript中的输入

这有可能吗?

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

您关闭'onclick'年初,注意'}'后'其他{...} '。 –

回答

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"); 
} 
+0

工作完美谢谢 –

+0

@MaxR欢迎您:) –

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; 
} 
+0

什么时候在这些情况下使用if语句切换有用?有没有性能优势?功能性好处? – Sir

+0

@Dave - 这更多是一种风格偏好。有些人(包括我)在超过两三个案例后会发现读起来更容易。它还清楚地表明,所有可能性都在测试相同的变量,而在if/else if/else if/else结构中,每个可能会测试完全不同的东西。 – nnnnnn

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"); 
} 
+0

可能默认不需要中断:) –

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> 

更少的代码和干净,希望它有助于

相关问题