我有一个div,它的内容一直在变化,是ajax请求,jquery函数,模糊等。
是否有一种方法可以在任何时间点检测我的div上的任何变化?
我不想使用任何间隔或默认值检查。
这样就可以了
$('mydiv').contentchanged() {
alert('changed')
}
我有一个div,它的内容一直在变化,是ajax请求,jquery函数,模糊等。
是否有一种方法可以在任何时间点检测我的div上的任何变化?
我不想使用任何间隔或默认值检查。
这样就可以了
$('mydiv').contentchanged() {
alert('changed')
}
当前回答
如果你不想使用定时器和检查innerHTML,你可以尝试这个事件
$('mydiv').on('DOMSubtreeModified', function(){
console.log('changed');
});
更多细节和浏览器支持数据在这里。
其他回答
使用MutationObserver,详见Mozilla提供的片段,并改编自这篇博客文章
或者,您也可以使用本链接中的JQuery示例
找到了,Chrome 18+,火狐14+
// 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();
如果你不想使用定时器和检查innerHTML,你可以尝试这个事件
$('mydiv').on('DOMSubtreeModified', function(){
console.log('changed');
});
更多细节和浏览器支持数据在这里。
尝试了上面给出的一些答案,但这些火灾发生了两次。如果你需要的话,这里有一个工作解决方案。
$('mydiv').one('DOMSubtreeModified', function(){
console.log('changed');
});
您正在寻找突变观察者或突变事件。它们既没有得到任何地方的支持,也没有被开发人员世界过于钟爱。
如果您知道(并且能够确保)div的大小将会改变,那么您可以使用跨浏览器调整大小事件。
您可以将div的旧innerHTML存储在一个变量中。设置检查旧内容与当前内容是否匹配的时间间隔。如果这不是真的,那就做点什么。