根据下拉列表中选择的内容隐藏和显示 HTML 元素

Hide and display HTML elements based on what was chosen in a dropdown

本文关键字:隐藏 显示 HTML 元素 下拉列表 选择      更新时间:2023-09-26

我的网站是在ASP classic - VBScript中创建的(不是我的选择,是我之前没有经验的语言)。我正在尝试创建一个网页,其中:下拉菜单根据第一个中选择的内容显示一个额外的下拉菜单。我正在尝试使用javascript函数来实现这一点。

例:

在第一个下拉列表中,用户选择冰淇淋或薯片。根据用户选择的内容,另一个下拉菜单给出了口味的选择。

冰淇淋:香草、巧克力、薄荷。
薯片:现成的咸味,奶酪和洋葱,盐和醋。

这是我的代码当前的样子:

.HTML

<select id="food" onchange="fctCheck(this.value)">
    <option value="">Choose an item</option>
    <option value="icecream">Ice cream</option>
    <option value="crisps">Crisps</option>
</select>  

<select id="icecream" style="display:none">
    <option value="vanilla">Vanilla</option>
    <option value="chocolate">Chocolate</option>
    <option value="mint">Mint</option>
</select>  

<select id="crisps" style="display:none">
    <option value="readysalted">Ready Salted</option>
    <option value="cheeseandonion">Cheese and Onion</option>
    <option value="saltandvinegar">Salt and Vinegar</option>
</select>  

.

JavaScript

function fctCheck(food)
    {
    if (food == "")
        {document.getElementById(food).style.display = "none";}
    else
        {document.getElementById(food).style.display = "block";}
    }

>正如 st3inn this.value 所提到的绝对没问题 - 只有 document.getElement==>B<==yId 的错别字。

但是您的代码有一个缺点,即用户可以同时选择这两个选项,因此两个子选择都可见。

您可以通过先隐藏所有子选择,然后再显示所选项目的子选择来避免这种情况。这可以通过这种方式完成(通过附加的name-attribute,或者,如果你选择使用jQuery,你可以做一些更复杂的事情):

JSFiddle 上的示例(带注释)

Javascript:

function fctCheck(food) {
    var elems = document.getElementsByName("subselector");
        for (var i = 0; i < elems.length; i++) {
            elems.item(i).style.display = "none";
        }
        document.getElementById(food).style.display = "block";
    }

.HTML:

<select id="food"onchange="fctCheck(this.value);">
    <option value="">Choose an item</option>
    <option value="icecream">Ice cream</option>
    <option value="crisps">Crisps</option>
</select>  

<select id="icecream" name="subselector" style="display:none">
    <option value="vanilla">Vanilla</option>
    <option value="chocolate">Chocolate</option>
    <option value="mint">Mint</option>
</select>  

<select id="crisps" name="subselector" style="display:none">
    <option value="readysalted">Ready Salted</option>
    <option value="cheeseandonion">Cheese and Onion</option>
    <option value="saltandvinegar">Salt and Vinegar</option>
</select>  

干杯
佛瑞恩

您需要

检查option值:

fctCheck(this.options[ this.options.selectedIndex ].value)

this.options 是当前<select><option>元素的集合,this.options.selectedIndex是显示当前选择的选项的整数值。

顺便说一句,您的代码中有拼写错误:

document.getElementbyId

应该是

document.getElementById

查看 jsFiddle 演示

你只是有一个错字。

function fctCheck(food)
{
    if (food == "") {
        document.getElementById(food).style.display = "none";}
    } else {
        document.getElementById(food).style.display = "block";
    }
}

应该工作。

this.value

相当于

this.options[this.options.selectedIndex].value