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

如何修复JavaScript中Cannot read properties of null (reading 'forEach')错误

错误原因及修复方案

报错根源

  • 你的HTML里只有空的<ul class="gallery"></ul>,没有任何<li>元素,所以document.querySelector("ul > li")找不到匹配节点,返回null,调用forEach自然触发Cannot read properties of null (reading 'forEach')错误。
  • 就算页面有li元素,querySelector只能返回第一个匹配项,不能用forEach遍历,批量获取元素得用querySelectorAll。
  • images数组定义不完整,缺失具体的url/alt值,也没闭合数组括号。
  • forEach回调里写的是字符串,不是有效JS代码,而且设置ul的列表样式根本不需要遍历li。

修复后的完整代码

HTML部分

<ul class="gallery"></ul>

JavaScript部分

// 补全你的图片数据,替换成实际的图片地址和描述
const images = [
  {
    url: "https://example.com/photo1.jpg",
    alt: "风景照片1"
  },
  {
    url: "https://example.com/photo2.jpg",
    alt: "风景照片2"
  }
];

// 设置页面背景色
document.body.style.backgroundColor = "#0009";
// 获取gallery容器
const galleryList = document.querySelector(".gallery");
// 直接给ul设置无列表样式
galleryList.style.listStyleType = "none";

// 遍历图片数组,动态生成li和img元素
images.forEach(imgData => {
  const listItem = document.createElement("li");
  const img = document.createElement("img");
  img.src = imgData.url;
  img.alt = imgData.alt;
  // 可按需给图片添加样式,比如控制尺寸
  img.style.width = "200px";
  listItem.appendChild(img);
  galleryList.appendChild(listItem);
});

核心修改点

  1. 补全images数组结构,填充实际的图片地址和描述,闭合数组括号。
  2. 直接获取目标ul元素,通过它直接设置listStyleType,无需遍历li。
  3. 遍历images数组动态创建li和img元素,把节点插入到ul中,确保页面存在li元素。
  4. 改用精准的类选择器定位ul,避免获取不存在的元素。

内容的提问来源于stack exchange,提问作者code grafo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:45:16