You need to enable JavaScript to run this app. 选中Espresso时禁用Single Origin等选项的JS代码无效求排查
优惠活动
大模型
产品
解决方案
定价
更多

选中Espresso时禁用Single Origin等选项的JS代码无效求排查

问题排查

你的代码存在3处核心错误:

  • 监听事件名错误:不存在change2事件,下拉框值变更的标准事件名为change
  • 多元素选择器语法错误:document.querySelectorAll接收多个选择器时需要把所有选择器写在同一个字符串内用逗号分隔,不能拆分为两个参数
  • NodeList集合不能直接设置属性:querySelectorAll返回的是元素集合,需要遍历集合中的每一个元素单独设置disabled属性

修复后完整代码

HTML部分

<td>
    <select class="type">
        <option value="Espresso">Espresso</option>
        <option value="" class="">Cappuccino</option>
        <option value="" class="">Americano</option>
        <option value="" class="">Pour over</option>
        <option value="Chemex" class="Chemex" id ="Chemex">Chemex</option>
    </select>
</td>
<td>
    <select class="coffe">
        <option value="" class="es">House espresso</option>
        <option value="" class="esp">Guest espresso</option>
        <option value="" class="ori">Single origin</option>
        <option value="" class="house">House blend</option>
    </select>
</td>

补充提示:原代码中写在Chemex option上的onChange="disableSize()"是无效配置,change事件只能绑定在select父元素上才能触发。

JS部分

const typeSelect = document.querySelector(".type");
const disableOptions = document.querySelectorAll(".ori, .house");

// 定义选项切换处理逻辑
function toggleCoffeeOptions() {
    const isEspressoSelected = typeSelect.value === "Espresso";
    disableOptions.forEach(option => {
        option.disabled = isEspressoSelected;
        // 可选优化:如果禁用时刚好选中了该选项,自动清空选中状态避免异常
        if (isEspressoSelected && option.selected) {
            option.parentElement.value = "";
        }
    })
}

// 绑定变更事件
typeSelect.addEventListener("change", toggleCoffeeOptions, false);
// 页面加载时触发一次,适配初始默认选中Espresso的场景
toggleCoffeeOptions();

内容的提问来源于stack exchange,提问作者Quang Anh Bui

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 15:24:03