我有一个在你点击按钮后呈现的输入元素,也就是说,它不会在页面加载时呈现. 当用户在元素中输入某些内容时,它应该会在控制台上记录"已点击添加按钮!". 但是,我收到以下错误消息:

Uncaught TypeError: can't access property "addEventListener", document.getElementById(...) is null

代码如下:

export const renderTodo = () => {
    document.querySelector('#main').innerHTML = `
<h2>Todo(CRUD) Page ${import.meta.env.VITE_TEST}</h2>
<br>
<form action="/action_page.php">
    <input type="text" placeholder="New todo.." id="new-todo">
    <br>
    <button id="add-todo">Add</button>
</form> 
`;
};

document.getElementById("new-todo").addEventListener("change", (e) => {
    console.log("Add button clicked!");
});

如何让addEventListener工作?

推荐答案

因为在它被附加到HTMLDOM之前,我们是trying to access,document.getElementById("new-todo"),因为function renderTodo()没有被调用,我们试图访问document.getElementById("new-todo").

export const renderTodo = () => {
    document.querySelector('#main').innerHTML = `
<h2>Todo(CRUD) Page ${import.meta.env.VITE_TEST}</h2>
<br>
<form action="/action_page.php">
    <input type="text" placeholder="New todo.." id="new-todo">
    <br>
    <button id="add-todo">Add</button>
</form> 
`;
// after the HTML string is parsed and attached in DOM then apply. It will be called whenever the function is called.
  document.getElementById("new-todo").addEventListener("change", (e) => {
      console.log("Add button clicked!");
  });
};

Javascript相关问答推荐

如何expose 像React在onChange、onClick等中所做的那样的参数?

使用print This时, map 容器已在LeafletJS中初始化

如何避免移动设备中出现虚假调整大小事件?

我试图实现用户验证的reduxstore 和操作中出了什么问题?

按钮未放置在html dis位置

通过嵌套模型对象进行Mongoose搜索

如何找出摆线表面上y与x相交的地方?

D3 Scale在v6中工作,但在v7中不工作

colored颜色 检测JS,平均图像 colored颜色 检测JS

为什么promise对js中的错误有一个奇怪的优先级?

禁用.js文件扩展名并从目录导入隐式根index.js时,找不到NodeJS导入模块

触发异步函数后不能显示数据

在Vercel中部署Next.js项目时获取`ReferenceError:未定义文档`

Reaction即使在重新呈现后也会在方法内部保留局部值

递增/递减按钮React.js/Redux

Django模板中未加载JavaScript函数

JQuery使用选项填充HTMLSELECT并设置默认结果,默认结果显示为空

$GTE的mongoose 问题

Firebase函数中的FireStore WHERE子句无法执行

material UI自动完成全宽