【问题标题】:Cannot get an img element that is dynamically added to a page无法获取动态添加到页面的 img 元素
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 这也能如我所愿!谢谢!您将如何包含对背景 img 的 css 检查:toCheck.css('background-image'),就像您在节点上执行 .find 一样?
  • 如果你想获得背景图像值,你可以使用$(image).css('background-image');而不是$(image).attr('src');,尽管img标签通常没有背景图像
  • 感谢您的帮助。
猜你喜欢
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 2015-12-19
  • 1970-01-01
  • 2020-09-09
  • 2020-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多