2013-05-16 71 views
0

是否有一个函数来检测是否已经对DOM进行了新的元素注入? 而不是我的Ajax调用后不断地检查,看看是否有注入像这样新的图像:jquery检测元素注入

$.ajax({ 
    ... 
    ... 
    success: function(data) { 
     $('.content').replaceWith(data); 
     if ($(data).find('img').length) alert('New images found!'); 
    } 
}); 

我一直希望有一个功能,在那里存在,检查是否有新的图片添加到DOM。例如:

$('img').injected(function() { 
    console.log('Found new images: ' + this); 
}); 
+0

可能重复:http://stackoverflow.com/questions/4765768/jquery-run-a-function-when-dom-changes – PeterFour

+0

可能重复:http://stackoverflow.com/questions/1091661/ detect-element-content-changes-with-jquery – slinky2000

回答

0

您可以通过突变观察者检测DOM变化。由于我不知道你的标记,我将使用通用元素。 .injectedElementParent是您想要注入img的家长。

// select the target node 
var target = document.querySelector('.injectedElementParent'); 

// create an observer instance 
var observer = new MutationObserver(function(mutations) { 
    mutations.forEach(function(mutation) { 
     console.log(mutation); 
    });  
}); 

// 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); 
+0

我得到“TypeError:Value not an object。”对于“var config = {...}”行 – user1105430

+0

您可以使用您的代码做一个小提琴吗? – Mircea