我使用Browserify处理JS中的模块(必需)。但是,当我在js文件中渲染元素并想在其上挂起事件(onclick)时,出现以下错误
Uncaught TypeError: Cannot set property 'onclick' of undefined
如何在以后出现在DOM中的元素上挂起事件?
如何在以后出现在DOM中的元素上挂起事件?
没有办法做到这一点。您应该更改应用程序的逻辑。您可以在父级上监听onClick事件。然后选择元素以选择所需的新元素。
您可以使用event delegation。基本上,您将事件侦听器添加到document
。在处理程序方法中,检查事件target
的区别属性。如果target
包含该属性,则执行某些操作,否则,什么也不会发生。这样,可以处理以后添加的元素。
// add a listener to document
document.addEventListener("click", showClick);
// ad a new element to the DOM
const newElement = document.createElement("div");
newElement.innerHTML = "I am new! Click me!";
newElement.id = "new";
newElement.style.cursor = "pointer";
document.body.appendChild(newElement);
// this handles all clicks
function showClick(evt) {
// if it's div#new, do something
if (evt.target.id === "new") {
console.log("there we are!");
}
// otherwise nothing happens
}
<div id="notnew">I exist after page load. Try clicking me, I dare you!</div>