简体   繁体   中英

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. 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. But it seems like I'm attaching an invalid function when the addEventListener is attached to my 'radio' element. 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. As stated in the comment,

The body of a function isn't evaluated until the function is called. There's no problem with access variables that are assigned between adding the event listener and triggering the event.

Question is answered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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