The child elements are not removed from their parent, so there's no remove event to observe.(子元素不会从其父元素中删除,因此没有观察到的remove事件。)
See:(看到:)
const ul = document.querySelector('ul'); const li = ul.children[0]; ul.remove(); console.log(li.parentElement);
<button class="RemoveListButton">Remove List</button> <div class="Container"> <ul class="ShoppingList"> <li class="Item">Pasta</li> <li class="Item">Chips</li> <li class="Item">Salsa</li> </ul> </div>
As you can see, the <li>
s still have a parent element of the .ShoppingList
, because the .ShoppingList
was removed from its container, but the individual <li>
s were not removed from the .ShoppingList
.(如您所见, <li>
仍然具有.ShoppingList
的父元素,因为.ShoppingList
已从其容器中删除,但各个<li>
并未从.ShoppingList
删除。)
If you wanted to see events for each removed <li>
, you'd have to iterate over and remove them explicitly in addition to removing the .ShoppingList
:(如果要查看每个删除的<li>
事件,除了删除.ShoppingList
之外,还必须遍历并显式删除它们:)
const removeWatcher = new MutationObserver(mutationList => { const removedNodes = mutationList.flatMap(m => [...m.removedNodes]) console.log('Removing', removedNodes) }) const container = document.querySelector('.Container') removeWatcher.observe(container, { subtree: true, childList: true }) const button = document.querySelector('.RemoveListButton') button.onclick = () => { document.querySelectorAll('.ShoppingList > li').forEach(li => li.remove()); document.querySelector('.ShoppingList').remove() } const listItems = document.querySelectorAll('.Item') listItems.forEach(item => item.onclick = () => { event.target.remove() })
<button class="RemoveListButton">Remove List</button> <div class="Container"> <ul class="ShoppingList"> <li class="Item">Pasta</li> <li class="Item">Chips</li> <li class="Item">Salsa</li> </ul> </div>
For what you want, either do that, or recursively flatten all children of every item in the removedNodes
array inside the observer callback.(为此,您可以执行此操作,也可以递归地将观察者回调内removedNodes
数组中每个项目的所有子项展平。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…