javascript - 无法获取动态添加到页面的 img 元素
问题描述
假设我试图在 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});
观察者有很多不同的元素,但我似乎在其中找不到任何 img 。
解决方案
您需要检查img
树的更深层次的元素,而不仅仅是mutation.children
(它们每个都可能包含其他子元素)的直接子元素。
您可以使用$.find('img')
, 并使用数组来消除重复项:
let imageList = [];
//want to do something useful in this function
function checkIfImg(toCheck) {
// find all images in changed node
let images = toCheck.find('img');
for(let image of images) {
let imageSource = $(image).attr('src');
if(!imageList.includes(imageSource)) {
imageList.push(imageSource);
console.log("image:", imageSource);
}
}
};
// get existing images
checkIfImg($(document));
// observe changes
var observer = new MutationObserver(function(mutations) {
mutations.forEach(mutation => checkIfImg($(mutation.target)));
});
observer.observe(document, { childList: true, subtree: true });
推荐阅读
- nginx - 使用 nginx 缓存 GZIPed 内容
- c++ - 延迟线程启动 - 通知所有未唤醒所有线程
- c# - Prism WPF 事件聚合器事件类替代
- r - 在 R 中跨列保留字符串的第一个实例
- python - 在列表字典的每个索引处查找最小值和最大值
- tiff - IDL 比较来自 Meteosat 的 1000 个 tif 并创建一个新的
- python - Openshift成功下载收集但构建失败
- ruby-on-rails - RSpec 测试 - slack bot ruby
- laravel - 是否可以在laravel中将vue js图表转换为pdf?
- javascript - 如何更新对象数组中的键值?