简体   繁体   中英

add event handlers every time a div changes

I am trying to add event handlers to a particular div that contains elements that change very often. There are different tabs and each tab renders different data from an API when clicked on The problem is that I need to add event handlers to some elements in each tab. When I add the event handler and the tab changes, the event handlers change also.

How do I:

  • Set an event handler only after the page has loaded
  • Every time the tab reloads

You can check for element/elements update, and if they have changed, use removeEventListener on your target.

Another not so efficient, but still working option would be using addEventListener function's third argument for options. {once: true} will make your event listener happen only once, and then you check, if the element/elements have changed, than you attach another listener, or reuse the same. More on MDN

I realized that I kept clearing the elements after I had selected them and then I was trying to update them even thought I had cleared them.

The solution is to to re-select them

for example: when my program starts, I select the elements like this:

const ele = document.querySelector(".class")

and then some where in the code, I clear the parent element like this:

document.querySelector(".parentElementClass").innerHTML = "";

after clearing, I then try to use the cleared element like this:

ele.addEventListener...

which is wrong and that is where the error comes form. What I have to do is to re-select the element again and then add the event listener like this:

const ele = document.querySelector(".class")
ele.addEventListener("...

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