简体   繁体   English

每次 div 更改时添加事件处理程序

[英]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.我正在尝试将事件处理程序添加到包含经常更改的元素的特定 div。 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.有不同的选项卡,每个选项卡在单击时呈现来自 API 的不同数据问题是我需要向每个选项卡中的某些元素添加事件处理程序。 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.您可以检查元素/元素更新,如果它们已更改,请在目标上使用removeEventListener

Another not so efficient, but still working option would be using addEventListener function's third argument for options.另一个效率不高但仍然有效的选项是使用addEventListener函数的第三个参数作为选项。 {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. {once: true}将使您的事件侦听器仅发生一次,然后您检查元素/元素是否已更改,然后附加另一个侦听器或重用相同的侦听器。 More on MDN更多关于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:例如:当我的程序启动时,我 select 的元素是这样的:

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("...

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

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