1

我有一个下拉列表,我想根据所选选项在其下方显示不同的表格。

我已经在这里看到了: Javascript - <option> 中的 onchange

我能够复制它,但我真的不知道如何添加更多选项/表格。

有人可以帮忙吗?这是到目前为止的代码:

<html>
<head>
<script type="text/javascript">
window.onload = function() {
    var eSelect = document.getElementById('transfer_reason');
    var optOtherReason = document.getElementById('otherdetail');
     eSelect.onchange = function() {
        if(eSelect.value === "other") {
            optOtherReason.style.display = 'block';
            } else {
            optOtherReason.style.display = 'none';
        }
    }
    var optOtherReason = document.getElementById('other2');
     eSelect.onchange = function() {
        if(eSelect.value === "z") {
            optOtherReason.style.display = 'block';
            } else {
            optOtherReason.style.display = 'none';
        }
    }
}
</script>
</head>
<body>
<select id="transfer_reason" name="transfer_reason">
<option value="">Motivo</option>
    <option value="x">Reason 1</option>
    <option value="y">Reason 2</option>
    <option value="z">Reason 3</option>
    <option value="other">Other Reason</option>
</select>
<br>
<table border="1" id="otherdetail" style="display: none;">
<tr>
<th>Versão 11</th><th>Versão 12</th><th>Justificativas</th>
</tr>
<tr>
<td> 1</td><td>Angelina</td><td>Delhi</td>
</tr>
</table>

<table border="1" id="other2" style="display: none;">
<tr>
<th>Versão 11</th><th>Versão 12</th><th>Justificativas</th>
</tr>
<tr>
<td> 1</td><td>Galeno</td><td>Delhi</td>
</tr>
</table>
</body>
</html>

就像现在一样,只有 id="other2" 的表正确加载,而另一个表没有。

4

1 回答 1

1

有比示例中存在的更好的方法。如果您在下拉列表中使用表 ID 值,那么整个事情会变得更容易。

<script type="text/javascript">
    window.onload = function() {
    var eSelect = document.getElementById('transfer_reason');
    var selVal;
    hideTables();
    eSelect.onchange = function() {
        hideTables();    
         selVal = eSelect[eSelect.selectedIndex].value;
        document.getElementById(selVal).style.display = "block";
    }

}

function hideTables() {
     var tables = document.getElementsByTagName("table");
    for(var x=0;x<tables.length;x++) {
        tables[x].style.display = "none";
    }
}    
 </script>

HTML:

  <select id="transfer_reason" name="transfer_reason">
        <option value="">Motivo</option>
        <option value="Table1">Reason 1</option>
        <option value="Table2">Reason 2</option>
        <option value="Table3">Reason 3</option>
        <option value="Table4">Other Reason</option>
</select>

<table id="Table1"><tr><td>#1#</td></tr></table>

<table id="Table2"><tr><td>#2#</td></tr></table> 

... etc ...
于 2012-09-18T19:10:47.870 回答