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

使用Parcel时无法为Input添加EventListener的问题求助

问题根源与解决方案

根本不是Parcel加载速度的问题,是你HTML代码里的重复id属性导致的DOM查找失败。

看你这段HTML代码:

<input class="form-control input-lg" id="inputlg" type="text" id="input1">

一个HTML元素只能有一个唯一的id属性,浏览器解析时只会保留第一个出现的id(也就是inputlg),你后面写的id="input1"会被直接忽略,所以JS里document.getElementById("input1")自然找不到对应的元素。

另外你第二个input也重复用了id="inputlg",这同样不符合规范,得改成唯一值。

修正后的代码

HTML部分

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./assets/scss/main.scss">
</head>

<body>
    <form>
        <div class="form-group">
            <!-- 修正label的for属性,和input的id对应 -->
            <label for="input1">input</label>
            <!-- 移除重复的id,只保留唯一的input1 -->
            <input class="form-control input-lg" id="input1" type="text">
            <!-- 修正第二个label的for属性,对应新的input id -->
            <label for="output">output</label>
            <!-- 给第二个input设置唯一id -->
            <input class="form-control input-lg" id="output" type="text">
        </div>
    </form>
    <script type="module" src="./assets/js/main.js" ></script>
</body>
</html>

JS部分(无需修改,只要HTML正确就能正常工作)

const input1 = document.getElementById("input1");
if(input1)
{
    console.log("The input exists");
    input1.addEventListener('click', () =>{
        console.log("heey");
    });
}

改完之后,再运行Parcel就能正常找到元素并绑定事件了,和服务器加载速度完全没关系,纯粹是HTML的语法错误导致的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 16:30:45