【发布时间】:2019-08-20 20:04:59
【问题描述】:
假设我正在尝试在 9gag 上运行以下代码以获取从无限滚动中动态添加的图像。我正在尝试弄清楚如何获取 img 元素。
//want to do something useful in this function
checkIfImg = function(toCheck){
if (toCheck.is('img')) {
console.log("finaly");
}
else {
backImg = toCheck.css('background-image');
if (backImg != 'none'){
console.log("background fynaly");
}
}
}
//that works just fine, since it is not for dynamic content
//$('*').each(function(){
// checkIfImg($(this));
//})
//this is sums up all my attempts
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
switch (mutation.type) {
case 'childList':
Array.prototype.forEach.call(mutation.target.children, function (child) {
if ( child.tagName === "IMG" ) {
console.log("img");
}
child.addEventListener( 'load', checkIfImg, false );
console.log("forEachChild");
console.log(child);
checkIfImg($(child));
$(child).each(function(){
console.log("inside each");
console.log($(this));
if ($(this).tagName == "IMG"){
console.log("img");
}
checkIfImg($(this));
})
});
break;
default:
}
});
});
observer.observe(document, {childList: true, subtree: true});
Observer 有很多不同的元素,但我似乎在其中找不到任何 img。
【问题讨论】:
-
img是插入节点的直接子节点吗?你试过mutation.target.querySelectorAll('img')吗? -
@msg 谢谢!
标签: javascript jquery html dom mutation-observers