【问题标题】:HTML Selection script between two droplists两个下拉列表之间的 HTML 选择脚本
【发布时间】:2012-02-14 17:06:36
【问题描述】:

我在使用标签构建的 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 的第一个元素,该函数无法正常工作。为什么?

【问题讨论】:

    标签: html select drop-down-menu


    【解决方案1】:

    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>
    

    【讨论】:

    • 感谢您的回答。我是一个 HTML 新手,虽然我之前在 Matlab 中使用过 switch-case 结构。
    • 没问题。作为一个参考,如果你使用了case 0case 1,......事情可能也会奏效。您缺少的主要内容是 selectedIndex 是从 0 开始的。我只是展示了一个适用于这种情况的快捷方式:)
    猜你喜欢
    • 2012-01-13
    • 2011-05-20
    • 1970-01-01
    • 2015-02-11
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 2012-07-17
    相关资源
    最近更新 更多