两个下拉列表之间的HTML选择脚本



我在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的第一个元素,该函数的作用是错误的。为什么?

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>

最新更新