简体   繁体   English

突变观察者下添加的元素在删除后会引发错误

[英]added element under mutation observer throws an error after removed

Hi,你好,

I have html code like this我有这样的 html 代码

<div id="box"></div>

then I have this observer so a function is executed if an element with data-added is added.然后我有这个观察者,所以如果添加了添加数据的元素,则会执行 function。

 new MutationObserver((mutations) => {
     for (let mutation of mutations) {
      if (mutation.type === 'childList' && mutation.addedNodes[0].dataset.added) {
       loadstuff();
      }
     }
    }).observe(box, {childList: true});

it works but as I remove the element I get this error on console:它可以工作,但是当我删除元素时,我在控制台上收到此错误:

Uncaught TypeError: mutation.addedNodes[0] is undefined未捕获的类型错误:mutation. addedNodes[0] 未定义

Fiddle here: https://jsfiddle.net/dc63r7bg/1/在这里小提琴: https://jsfiddle.net/dc63r7bg/1/

How can I get rid of that error?我怎样才能摆脱这个错误?

Thank you.谢谢你。

You can use the optional chaining operator :您可以使用可选的链接运算符

 var box = document.getElementById("box"); function addit() { box.insertAdjacentHTML('afterbegin', '<span id="elm" data-added="yes">element</span>'); } function removeit() { document.getElementById("elm").remove(); } new MutationObserver((mutations) => { for (let mutation of mutations) { if (mutation.type === 'childList' && mutation.addedNodes[0]?.dataset.added) { console.log('added'); } } }).observe(box, { childList: true });
 <div id="box"></div> <button onclick="addit()">Add</button> <button onclick="removeit()">Remove</button>

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

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