You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在动态插入含lazyLoad类的img元素后选中该元素?

如何在动态插入带有lazyLoad类的图片后选中它们?

问题核心是异步执行顺序不匹配:window.onload在页面所有静态资源加载完成后就触发,但你的API请求是异步操作,插入DOM的逻辑会在window.onload之后才完成,所以此时调用querySelectorAll(".lazyLoad")自然拿不到元素。

给你三种可行的解决办法:

1. 在DOM插入完成后立即处理

直接在spoonacular函数内,等所有动态内容插入到DOM后,马上获取图片并执行懒加载逻辑:

const spoonacular = async () => {
  const response = await fetch(
    "https://api.spoonacular.com/recipes/complexSearch?apiKey=c0c692d2b8be4e92a29883049789419b&includeNutrition=true.",
    {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    }
  );

  const data = await response.json();

  data.results.forEach((e) => {
    const html = `
    <div class="dish" id="a${e.id}">
      <a href="recipe/${e.id}"><img src=${e.image} alt="" class="dishImg lazyLoad" /></a>
      <h2 class="dishTitle">
        ${e.title}
      </h2>
  </div>
    `;
    dishes.insertAdjacentHTML("afterbegin", html);
  });

  // 关键:所有内容插入后立即获取图片
  const images = document.querySelectorAll(".lazyLoad");
  console.log(images);
  // 这里可以直接调用你的懒加载初始化代码
};

2. 用MutationObserver监听DOM变化

如果无法直接修改spoonacular函数的逻辑,可以用MutationObserver监听dishes容器的变化,当有新元素插入时自动捕获图片:

// 创建观察者实例
const observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    // 检查是否有新增节点
    if (mutation.addedNodes.length > 0) {
      const images = document.querySelectorAll(".lazyLoad");
      console.log(images);
      // 执行懒加载逻辑
    }
  });
});

// 开始监听dishes容器的子节点变化
observer.observe(document.getElementById('dishes'), {
  childList: true, // 监听子节点的添加/移除
  subtree: true // 若需要监听子容器内的变化则开启
});

3. 等待异步函数执行完成后再查询

如果spoonacular是在window.onload之后才调用的,可把window.onload改成异步函数,等待API请求和DOM插入完成后再查询:

window.onload = async function () {
  // 等待spoonacular执行完毕
  await spoonacular();
  const images = document.querySelectorAll(".lazyLoad");
  console.log(images);
};

三种方案里,第一种最直接高效,完全贴合你的代码执行流程,不需要额外的监听逻辑。

内容的提问来源于stack exchange,提问作者Aasem Shoshari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:55:09