簡體   English   中英

無法獲取動態添加到頁面的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});

觀察者有很多不同的元素,但是我似乎在其中找不到任何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 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM