2015-09-05 142 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> 

更少的代碼和乾淨,希望它有助於

相關問題