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

JavaScript事件不生效,切换下拉选项后h1标签颜色不改变如何解决?

问题原因

你的代码问题出在事件名称拼写错误:你写的DOMContentloaded(末尾的l为小写)不是标准的DOM加载完成事件名,正确的拼写是DOMContentLoaded(末尾的L为大写)。浏览器无法识别错误的事件名,所以内部绑定select标签onchange事件的逻辑从未执行,切换下拉选项自然不会触发颜色修改。

修正后代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Select tag</title>
    <script>
        // 仅修改了事件名的拼写,将小写l改为大写L
        document.addEventListener('DOMContentLoaded', () => {
            document.querySelector('select').onchange=function(){
                document.querySelector('#hello').style.color=this.value;
            }
        });
    </script>
</head>

<body>
    <h1 id="hello">Hello!</h1>
    <select name="select" id="select">
        <option value="black">Black</option>
        <option value="red">Red</option>
        <option value="blue">Blue</option>
    </select>
</body>

</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:45:09