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

时间:2019-08-20 20:04:59

标签: javascript jquery html dom mutation-observers

比方说,我正在尝试在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。

1 个答案:

答案 0 :(得分:0)

您需要检查树深处的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 });