You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据<select>选择项展示对应<div>内容?

原生JavaScript实现下拉选择对应内容展示

先调整HTML(可选但更清晰)

原代码里有两个选项的value都是Option C,会导致无法区分「Language」和「Stationary」,建议先把最后一个选项的value改成唯一值,同时给每个输出div加data-match属性,明确和下拉选项的对应关系:

<div id="main-container">
    <select name="" id="user-selector" class="selector-dropdown">
        <option selected="true" style='display: none'>Select</option>
        <option value="Option A">Fruit</option>
        <option value="Option B">Animal</option>
        <option value="Option C">Language</option>
        <option value="Option D">Stationary</option>
    </select>

    <div class="output" data-match="Option A">Orange</div>
    <div class="output" data-match="Option B">Lion</div>
    <div class="output" data-match="Option C">English</div>
    <div class="output" data-match="Option D">Pen</div>
</div>

原生JavaScript代码(适合新手理解)

// 1. 获取页面上的下拉框和所有输出div
const selector = document.getElementById('user-selector');
const outputDivs = document.querySelectorAll('.output');

// 2. 给下拉框绑定「选择变化」事件
selector.addEventListener('change', function() {
    // 3. 获取当前选中选项的value值
    const selectedValue = this.value;

    // 4. 先隐藏所有输出div
    outputDivs.forEach(div => {
        div.style.display = 'none';
    });

    // 5. 如果选中了有效选项(不是默认的Select),显示对应内容
    if (selectedValue) {
        const targetDiv = document.querySelector(`.output[data-match="${selectedValue}"]`);
        if (targetDiv) {
            targetDiv.style.display = 'block';
        }
    }
});

代码简单解释

  • document.getElementById:通过ID获取页面元素,方便后续操作
  • querySelectorAll('.output'):获取所有带output类的div,得到一个可遍历的集合
  • addEventListener('change', ...):监听下拉框的选择变化,用户选不同选项时自动执行内部代码
  • forEach:遍历所有输出div,统一隐藏
  • querySelector(.output[data-match="${selectedValue}"]):根据选中的value,找到对应data-match属性的div并显示

不修改原HTML的替代方案(靠顺序对应)

如果不想改原HTML,可通过选项的索引和输出div的顺序对应(下拉框第1个有效选项对应第1个output,以此类推):

const selector = document.getElementById('user-selector');
const outputDivs = document.querySelectorAll('.output');

selector.addEventListener('change', function() {
    const selectedIndex = this.selectedIndex;
    
    // 隐藏所有div
    outputDivs.forEach(div => div.style.display = 'none');
    
    // 下拉框索引0是默认选项,索引1对应第1个output(索引0)
    if (selectedIndex > 0) {
        outputDivs[selectedIndex - 1].style.display = 'block';
    }
});

内容的提问来源于stack exchange,提问作者user20695651

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:35:22