我有一个div,它的内容一直在变化,是ajax请求,jquery函数,模糊等。
是否有一种方法可以在任何时间点检测我的div上的任何变化?
我不想使用任何间隔或默认值检查。
这样就可以了
$('mydiv').contentchanged() {
alert('changed')
}
我有一个div,它的内容一直在变化,是ajax请求,jquery函数,模糊等。
是否有一种方法可以在任何时间点检测我的div上的任何变化?
我不想使用任何间隔或默认值检查。
这样就可以了
$('mydiv').contentchanged() {
alert('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();
其他回答
由于$("#selector").bind()已弃用,您应该使用:
$("body").on('DOMSubtreeModified', "#selector", function() {
// code here
});
domsubtremodified不是一个好的解决方案。如果您决定在事件处理程序中更改DOM,它可能会导致无限循环,因此它在许多浏览器中已被禁用。MutationObserver是更好的答案。
MDN医生
const onChangeElement = (qSelector, cb)=>{
const targetNode = document.querySelector(qSelector);
if(targetNode){
const config = { attributes: true, childList: false, subtree: false };
const callback = function(mutationsList, observer) {
cb($(qSelector))
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
}else {
console.error("onChangeElement: Invalid Selector")
}
}
你可以这样使用它,
onChangeElement('mydiv', function(jqueryElement){
alert('changed')
})
您可以将div的旧innerHTML存储在一个变量中。设置检查旧内容与当前内容是否匹配的时间间隔。如果这不是真的,那就做点什么。
你可以试试这个
$('.myDiv').bind('DOMNodeInserted DOMNodeRemoved', function() {
});
但这在ie浏览器中可能行不通,我还没测试过
Adding some content to a div, whether through jQuery or via de DOM-API directly, defaults to the .appendChild() function. What you can do is to override the .appendChild() function of the current object and implement an observer in it. Now having overridden our .appendChild() function, we need to borrow that function from an other object to be able to append the content. Therefor we call the .appendChild() of an other div to finally append the content. Ofcourse, this counts also for the .removeChild().
var obj = document.getElementById("mydiv");
obj.appendChild = function(node) {
alert("changed!");
// call the .appendChild() function of some other div
// and pass the current (this) to let the function affect it.
document.createElement("div").appendChild.call(this, node);
}
};
在这里您可以找到一个naïf示例。我想你们可以自己扩展。 http://jsfiddle.net/RKLmA/31/
顺便说一下:这表明JavaScript遵循openclose原则。:)