删除和添加子元素时是否会触发事件?

h3n*_*h3n 4 javascript jquery

说我有<ul>,我需要在<li>删除和添加时监听/观看。

Jac*_*_Hu 7

当然,您可以使用 aMutationObserver来监视 DOM 元素中的更改。

在这个答案中描述它的实现有点复杂,但是 MDN 文章应该为您提供所需的所有信息。

这是一个人为的、部分被盗的例子,可以给你一个想法:

const btnAdd = document.getElementById('btn-add');
const btnRemove = document.getElementById('btn-remove');

// Select the node that will be observed for mutations
const targetNode = document.getElementById('some-id');

btnAdd.addEventListener('click', () => {
  const li = document.createElement('li');
  targetNode.appendChild(li);
});

btnRemove.addEventListener('click', () => {
  targetNode.removeChild(targetNode.children[0]);
});


// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function(mutationList, observer) {
    // Use traditional 'for loops' for IE 11
    for (const mutation of mutationList) {
        if (mutation.type === 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type === 'attributes') {
            console.log(`The ${mutation.attributeName} attribute was modified.`);
        }
    }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);
Run Code Online (Sandbox Code Playgroud)
<button id="btn-add">Add Item</button>
<button id="btn-remove">Remove Item</button>
<ul id="some-id"></ul>
Run Code Online (Sandbox Code Playgroud)