我想执行一个函数时,一些div或输入被添加到html。 这可能吗?
例如,添加了一个文本输入,然后应该调用函数。
我想执行一个函数时,一些div或输入被添加到html。 这可能吗?
例如,添加了一个文本输入,然后应该调用函数。
当前回答
下面的例子改编自Mozilla Hacks的博客文章,并使用MutationObserver。
// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
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
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
浏览器支持:Chrome 18+, Firefox 14+, IE 11+, Safari 6+
其他回答
使用MutationObserver界面,如Gabriele Romanato的博客所示
找到了,Chrome 18+,火狐14+
// The node to be monitored
var target = $( "#content" )[0];
// Create an observer instance
var observer = new MutationObserver(function( mutations ) {
mutations.forEach(function( mutation ) {
var newNodes = mutation.addedNodes; // DOM NodeList
if( newNodes !== null ) { // If there are new nodes added
var $nodes = $( newNodes ); // jQuery set
$nodes.each(function() {
var $node = $( this );
if( $node.hasClass( "message" ) ) {
// do something
}
});
}
});
});
// Configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true
};
// Pass in the target node, as well as the observer options
observer.observe(target, config);
// Later, you can stop observing
observer.disconnect();
8年后,这是我使用MutationObserver和RxJS的解决方案
observeDOMChange(document.querySelector('#dom-changes-here'))
.subscribe(val => log('DOM-change detected'));
与其他方法的主要区别是在DOM更改时触发CustomEvent,并通过以下特性侦听事件的恢复以有效地执行用户逻辑;
撤消连续的DOM更改,以防止执行过多 在给定的时间后停止观看 在停止监视DOM更改后删除事件侦听器/订阅者 观察一个框架(比如Angular)中发生的DOM变化是很有用的
import { fromEvent, timer} from 'rxjs';
import { debounceTime, takeUntil, tap } from 'rxjs/operators';
function observeDOMChange(el, options={}) {
options = Object.assign({debounce: 100, expires: 2000}, options);
const observer = new MutationObserver(list => {
el.dispatchEvent(new CustomEvent('dom-change', {detail: list}));
});
observer.observe(el, {attributes: false, childList: true, subtree: true });
let pipeFn;
if (options.expires) {
setTimeout(_ => observer.disconnect(), options.expires);
pipeFn = takeUntil(timer(options.expires));
} else {
pipeFn = tap(_ => _);
}
return fromEvent(el, 'dom-change')
.pipe(pipeFn, debounceTime(options.debounce));
}
在stackblitz演示。
2015年更新,新的MutationObserver被现代浏览器支持:
找到了,Chrome 18+,火狐14+
如果您需要支持较老的方法,您可以尝试使用其他方法,例如下面这个5年(!)年前的答案中提到的方法。那里有龙。享受:)
其他人正在更改文档?因为如果你可以完全控制这些变化,你只需要创建你自己的domChanged API——用一个函数或自定义事件——并在你修改东西的地方触发/调用它。
DOM Level-2有突变事件类型,但是旧版本的IE不支持它。请注意,突变事件在DOM3事件规范中已弃用,并且具有性能损失。
你可以尝试在IE中使用onpropertychange来模拟突变事件(如果它们都不可用,则退回到蛮力方法)。
对于一个完整的domChange,间隔可能是一个过度杀死。假设您需要存储整个文档的当前状态,并检查每个元素的每个属性是否相同。
也许如果您只对元素及其顺序感兴趣(如您在问题中提到的),getElementsByTagName("*")可以工作。如果您添加一个元素,删除一个元素,替换元素或更改文档的结构,这将自动触发。
我写了一个概念证明:
(function (window) {
var last = +new Date();
var delay = 100; // default delay
// Manage event queue
var stack = [];
function callback() {
var now = +new Date();
if (now - last > delay) {
for (var i = 0; i < stack.length; i++) {
stack[i]();
}
last = now;
}
}
// Public interface
var onDomChange = function (fn, newdelay) {
if (newdelay) delay = newdelay;
stack.push(fn);
};
// Naive approach for compatibility
function naive() {
var last = document.getElementsByTagName('*');
var lastlen = last.length;
var timer = setTimeout(function check() {
// get current state of the document
var current = document.getElementsByTagName('*');
var len = current.length;
// if the length is different
// it's fairly obvious
if (len != lastlen) {
// just make sure the loop finishes early
last = [];
}
// go check every element in order
for (var i = 0; i < len; i++) {
if (current[i] !== last[i]) {
callback();
last = current;
lastlen = len;
break;
}
}
// over, and over, and over again
setTimeout(check, delay);
}, delay);
}
//
// Check for mutation events support
//
var support = {};
var el = document.documentElement;
var remain = 3;
// callback for the tests
function decide() {
if (support.DOMNodeInserted) {
window.addEventListener("DOMContentLoaded", function () {
if (support.DOMSubtreeModified) { // for FF 3+, Chrome
el.addEventListener('DOMSubtreeModified', callback, false);
} else { // for FF 2, Safari, Opera 9.6+
el.addEventListener('DOMNodeInserted', callback, false);
el.addEventListener('DOMNodeRemoved', callback, false);
}
}, false);
} else if (document.onpropertychange) { // for IE 5.5+
document.onpropertychange = callback;
} else { // fallback
naive();
}
}
// checks a particular event
function test(event) {
el.addEventListener(event, function fn() {
support[event] = true;
el.removeEventListener(event, fn, false);
if (--remain === 0) decide();
}, false);
}
// attach test events
if (window.addEventListener) {
test('DOMSubtreeModified');
test('DOMNodeInserted');
test('DOMNodeRemoved');
} else {
decide();
}
// do the dummy test
var dummy = document.createElement("div");
el.appendChild(dummy);
el.removeChild(dummy);
// expose
window.onDomChange = onDomChange;
})(window);
用法:
onDomChange(function(){
alert("The Times They Are a-Changin'");
});
这适用于IE 5.5+, FF 2+, Chrome, Safari 3+和Opera 9.6+
使用TrackChanges来检测html更改。 链接:https://www.npmjs.com/package/track-changes-js
例子
let button = document.querySelector('.button');
trackChanges.addObserver('buttonObserver', () => button);
trackChanges.addHandler('buttonObserver', buttonHandler);
function buttonHandler(button) {
console.log(`Button created: ${button}`);
}
下面的例子改编自Mozilla Hacks的博客文章,并使用MutationObserver。
// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
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
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
浏览器支持:Chrome 18+, Firefox 14+, IE 11+, Safari 6+