2012-01-20 16 views
1

我有兩個使用標記構建的html droplist。兩個列表之間的HTML選擇腳本

<select name="List1" id="List1" onclick="GetVal()"> 
<option value="1" selected="selected">Mercurio</option> 
<option value="2">Venus</option> 
<option value="3">Tierra</option> 
<option value="4">Marte</option> 
</select> 

<select name="List2" id="List2"> 
<option value="1" selected="selected">Hg</option> 
<option value="2">Ve</option> 
<option value="3">Ti</option> 
<option value="4">Ma</option> 
</select> 

我已經寫了一個腳本,例如從List2中選擇元素的選擇依賴於List1對應元素的選擇。

<script language="javascript" type="text/javascript"> 
// <!CDATA[ 
function GetVal() { 
var LSelect1 = document.getElementById('List1'); 
var LSelect2 = document.getElementById('List2'); 
switch (LSelect1.selectedIndex) 
{ 
case 1: 
    LSelect2.selectedIndex = 1; 
    break; 
case 2: 
    LSelect2.selectedIndex = 2; 
    break; 
case 3: 
    LSelect2.selectedIndex = 3; 
    break; 
default: 
    LSelect2.selectedIndex = 4; 
} 
} 
// ]]> 
</script> 

但是,該函數對List1的第一個元素錯誤地工作。爲什麼?

回答

2

selectedIndex是從0開始的。一個更簡單的方法可能是這樣的:

<script language="javascript" type="text/javascript"> 
// <!CDATA[ 
function GetVal() { 
    var LSelect1 = document.getElementById('List1'); 
    var LSelect2 = document.getElementById('List2'); 

    LSelect2.selectedIndex = LSelect1.selectedIndex; 
} 
// ]]> 
</script> 
+0

謝謝你的回答。儘管我在Matlab中使用過開關盒結構,但我仍然是HTML的新手。 – julian

+0

沒問題。作爲一個fyi,如果你使用了'case 0','case 1',...事情可能會起作用。你缺少的主要是'selectedIndex'是從0開始的。我只是顯示了一個適用於這種情況的快捷方式:) – dana