检测 DOM 更改
您可以使用各种方法检测文档对象模型 (DOM) 的更改。
1。 MutationObserver(现代浏览器)
const observer = new MutationObserver((mutations) => { // Process mutations here... }); observer.observe(targetElement, { childList: true, subtree: true });
2.突变事件(已弃用,但仍然支持)
targetElement.addEventListener('DOMNodeInserted', (event) => { // Node added }); targetElement.addEventListener('DOMNodeRemoved', (event) => { // Node removed });
示例:检测输入添加
如果您特别想在
const targetElement = document.getElementById('element-to-monitor'); const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.type === 'childList' && mutation.addedNodes.length > 0) { const addedNodes = mutation.addedNodes; Array.from(addedNodes).forEach((node) => { if (node.nodeName === 'DIV' || node.nodeName === 'INPUT') { // Execute your function here... } }); } }); }); observer.observe(targetElement, { childList: true, subtree: true });
以上是如何在 JavaScript 中检测并响应 DOM 更改?的详细内容。更多信息请关注PHP中文网其他相关文章!