我目前正在开发一个辅助项目,并正在使用DOM操作。

在下面,我创建了一个函数addImage。浏览器调用此函数时,它将返回以下错误:


  TypeError:无法在“节点”上执行“ appendChild”:参数1的类型不是“节点”。


function addImage(data) {
    let imageElement = new Image();
    imageElement.src = data;
    console.log(imageElement);
    let imageContainer = document.getElementById('image-container');
    imageContainer.appendChild('imageElement');
}

imageElement = `<img src="https://igcdn-photos-f-a.akamaihd.net/hphotos-ak-xpt1/t51.2885-19/11193017_906607852718693_821675199_a.jpg">`


我用这个typeError看了其他问题。在这些示例中,字符串被添加到div元素中。

最佳答案

您使用Node.appendChild()imageElement附加到imageContainer,应将元素(节点)传递到appendChild(),但是您传递了string,这就是错误的原因。

所以,改变

imageContainer.appendChild('imageElement');




imageContainer.appendChild(imageElement);


而且你很好。

Working example

10-07 14:28