首页 > 解决方案 > 使用 javascript createElement() 将 imgs 附加到 div 时出现错误消息“无法读取 null 的属性‘appendChild’”

问题描述

这里是 js 新手。我想将每个图像标签(其中 15 个)附加到它自己的 div 标签中。但是,我在控制台中遇到了“无法读取 null 的属性 'appendChild'”错误。

function createImage()
{
    const DIV_ID = ['b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'b10', 'b11', 'b12',
    'b13', 'b14', 'b15'];

    img = [];
    container = [];

    width = 120;
    height = 120;

    var src = "rdmImg.png";
    for (i = 0; i < 15; i++)
    {
        container[i] = document.createElement('div');
        container[i].setAttribute = ("id", `${DIV_ID[i]}`);
        document.body.appendChild(container[i]);

        img[i] = document.createElement('img'); 
        img[i].src = src;
        img[i].width = width;
        img[i].height = height;
        document.getElementById(`${DIV_ID[i]}`).appendChild(img[i]); //Cannot read property of null
    }

非常感谢任何手!

标签: javascripthtmlloopsdynamicappendchild

解决方案


推荐阅读