无法获取动态添加到页面的 img 元素

Cannot get an img element that is dynamically added to a page

假设我正在尝试 运行 在 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.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 });