我有一个输入元素,在单击按钮后呈现,即它不会在页面加载时呈现。 当用户在元素中键入内容时,应该控制台日志“单击添加按钮!”。 但是,我收到以下错误消息:
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 工作?
最佳答案
抛出错误,因为我们在附加到之前尝试访问 document.getElementById("new-todo")
HTML DOM,因为 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 - 如何为不在页面加载时呈现的元素创建 addEventListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76995575/