2012-12-30 28 views
2

我有一個選擇框有三個不同的選項(真正與空白的一個4),我點擊一個按鈕後,我需要一個警告框來顯示一條消息。這裏有一些代碼。If..else ..與選擇框值javascript和html

HTML:

<select id="item1" name="Item 1"> 
     <option></option> 
     <option value="1">Camera</option> 
     <option value="2">Microphone</option> 
     <option value="3">Tripod</option> 
    </select> 

    <button onclick="message()">Go!</button> 

的Javascript:

<SCRIPT language = javascript> 

function message() { 

var s = document.getElementById('item1'); 
var item1 = s.options[s.selectedIndex].value; 

if (item1 = 1) { 
    alert("it equals camera") 
} 
else if (item1 = 2) { 
    alert("it equals microphone") 
} 
else if (item1 = 3) { 
    alert("it equals tripod") 
} 
} 

</SCRIPT> 

我每次點擊的警告框說: 「這等於相機」 按鈕。我可以選擇麥克風,然後單擊按鈕,它仍會這樣說。

如果我把

alert(item1) 

中會顯示1,2,或3所以我假設它的東西用的if..else功能..語句。

回答

1

替換

if (item1 = 1) { 

if (item1 == 1) { 

(和相同的其他的)

item = 1改變的item1值,並返回1,其評估作爲true在測試。

但請注意,你可以更有效地

  • 使用開關
  • 或讀取值直接

例如:

document.getElementById('item1').onchange = function(){ 
    alert("it equals " + this.options[this.selectedIndex].innerHTML);   
}​​​​​​​​ 

Demonstration

+0

雙等於所有三個'如果' –

+0

好天啊!這更像是一個聊天室!感謝你及時的答覆。 –

2

記住使用==代替=

if(item == 1) 

,而不是

if(item = 1) 
1

在JavaScript(任何幾乎所有其他的花括號語言)的單=總是意味着分配。因此,您將值1指定爲item1

你想要比較運營商是==

function message() { 
    var s = document.getElementById('item1'); 
    var item1 = s.options[s.selectedIndex].value; 

    if(item1 == '1') { 
     alert("it equals camera") 
    } else if(item1 == '2') { 
     alert("it equals microphone") 
    } else if(item1 == '3') { 
     alert("it equals tripod") 
    } 
} 

下面是其他一些建議,以改善你的代碼:

  • 不要使用<script>棄用的language屬性。只要<script>適用於JavaScript或<script type="text/javascript>,如果您想明確說明。
  • 請勿使用內聯事件。使用addEventListener()方法而不是onclick="..."註冊事件處理程序。
4

在JavaScript中,我們應該使用===,這檢查數據類型也。

0

爲什麼不使用這種方法,當您的選擇器獲取更多項目時更容易?

var s = document.getElementById("item1"); 
var item1 = s.options[s.selectedIndex].text; 
window.alert('it equals '+item1); 

編輯:JSFiddle

編輯2:更改===解決您的問題。而不是使用s.options[s.selectedIndex].value,你可以簡單地使用s.selectedIndex。這也將返回1,2或3,這更容易理解。