簡體   English   中英

突變觀察者下添加的元素在刪除后會引發錯誤

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

你好,

我有這樣的 html 代碼

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

然后我有這個觀察者,所以如果添加了添加數據的元素,則會執行 function。

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

它可以工作,但是當我刪除元素時,我在控制台上收到此錯誤:

未捕獲的類型錯誤:mutation. addedNodes[0] 未定義

在這里小提琴: https://jsfiddle.net/dc63r7bg/1/

我怎樣才能擺脫這個錯誤?

謝謝你。

您可以使用可選的鏈接運算符

 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