简体   繁体   English

在 JavaScript 中引用另一个元素的事件侦听器中尚未创建的元素

[英]Referencing a yet to be created element in another element's event listener in JavaScript

I have an element created dynamically, for which I have already attached an event listener to, like below:我有一个动态创建的元素,我已经为其附加了一个事件侦听器,如下所示:

radio.addEventListener('click', (event) => {
   document.getElementById(action[1]).style.display = 'block';
});

The 'action[1]' is a string which will be the id of an element yet to be created. 'action[1]' 是一个字符串,它将是尚未创建的元素的 ID。 I have tried this, and it seems to work.我试过这个,它似乎有效。 I know the event listener's function will only be fired on the 'click' event, and by then the 'action[1]' element will exist.我知道事件侦听器的 function 只会在“点击”事件时触发,到那时“action[1]”元素将存在。 But it seems like I'm attaching an invalid function when the addEventListener is attached to my 'radio' element.但是当 addEventListener 附加到我的“radio”元素时,我似乎附加了一个无效的 function。 Will this cause problems?这会导致问题吗?

Okay, I want to close this with an answer, but the answer, comes from Barmar, so I don't take credit for it.好吧,我想用一个答案来结束这个,但是答案来自 Barmar,所以我不认为这是功劳。 As stated in the comment,如评论中所述,

The body of a function isn't evaluated until the function is called.在调用 function 之前,不会评估 function 的主体。 There's no problem with access variables that are assigned between adding the event listener and triggering the event.在添加事件侦听器和触发事件之间分配的访问变量没有问题。

Question is answered.问题得到解答。

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

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