简体   繁体   English

将事件侦听器添加到新添加的DOM元素中

[英]Adding event listener to a newly added DOM element

How do you call an ID that was created through js using a function, but wasn't part of the initial html 如何调用通过js使用函数创建的ID,但该ID并非初始html的一部分

var topic1 = document.createElement("div")
document.body.appendChild(topic1)

we tried using an eventlistener 我们尝试使用事件监听器

var ff15 = document.getElementById("topic1")
if(ff15){
    ff15.addEventListener("click", response1)
}

but it does not work. 但它不起作用。

You can use the variable topic1 directly to bind an event listener to it. 您可以直接使用变量topic1将事件侦听器与其绑定。 You don't have to get to that element again using document.getElementById . 您不必使用document.getElementById再次到达该元素。

It could be something as follows: 可能如下所示:

 var topic1 = document.createElement("div"); topic1.innerText = "Some text"; document.body.appendChild(topic1); topic1.addEventListener("click", function() { alert("Clicked"); }); 

Add an id to the div if you want to use getElementById . 如果要使用getElementById ,则向div添加一个id

const topic1 = document.createElement('div');
topic1.id = 'topic1';
document.body.appendChild(topic1);

const item = document.getElementById('topic1');
item.addEventListener('click', () => {
  alert('what');
});

But you can just use topic1 directly if you're not doing anything else. 但是,如果您没有执行其他任何操作,则可以直接使用topic1

topic1.addEventListener('click', () => {
  alert('what');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM