HTML下拉菜单,用于填充另一个下拉菜单

时间:2014-04-09 22:32:25

标签: javascript php jquery html css

类似于下面的示例,一旦用户点击第一个下拉菜单,下面的第二个下拉菜单会发生变化:

<select id="opts" onchange="showForm()">
    <option value="0">Select Option</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>

<div id="f1" style="display:none">
    <form name="form1">
        <select id="opts" onchange="showForm()">
            <option value="0">Select Option</option>
            <option value="1">Option 1A</option>
            <option value="2">Option 1B</option>
        </select>
    </form>
</div>

<div id="f2" style="display:none">
    <form name="form2">
        <select id="opts" onchange="showForm()">
            <option value="0">Select Option</option>
            <option value="1">Option 2A</option>
            <option value="2">Option 2B</option>
        </select>
    </form>
</div>

<script type="text/javascript">
    function showForm() {
        var selopt = document.getElementById("opts").value;
        if (selopt == 1) {
            document.getElementById("f1").style.display = "block";
            document.getElementById("f2").style.display = "none";
        }
        if (selopt == 2) {
            document.getElementById("f2").style.display = "block";
            document.getElementById("f1").style.display = "none";
        }
        if (selopt == 0) {
            document.getElementById("f2").style.display = "none";
            document.getElementById("f1").style.display = "none";
        }
    }

上面的代码完全按照预期运行 - 但是我将有超过100个不同的下拉列表和来自php的大量数据库结果,我可以看到这种方法意味着大量浪费的标记。有没有更聪明的方法来实现上述相同的功能?

0 个答案:

没有答案
相关问题