【发布时间】:2021-10-21 18:11:23
【问题描述】:
我正在尝试通过 JS 在该 div 中插入一个新的 Div 和一个 img。我创建了一个类,稍后我将在其中使用一个函数,该函数应该被调用以使用该函数并插入图像。这样做时,我不断得到Uncaught TypeError: Cannot read properties of null (reading 'appendChild') HTML 和 JS 下面:
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Actividad 3</title>
<script type="text/javascript" src="actividad3.js"></script>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="style.css">
<body >
<h2>EXTRAS DISPONIBLES</h2>
</body>
</html>
JS
class extra {
precio = "10€";
url = "concha_azul.jpeg";
constructor(precio, url) {
this.precio = precio;
this.url = url;
}
getHTML = function () {
console.log("hello");
var newDiv = document.createElement("div");
newDiv.id = "x";
var div = document.getElementById("x");
var img = document.createElement("img");
img.src = "concha_azul.jpeg";
div.appendChild(img);
}
}
let miExtra = new extra();
miExtra.getHTML();
【问题讨论】:
-
为什么会有
var div = document.getElementById("x");这一行??在将其附加到 dom 之前,您无法获得该属性.. 尝试类似newDiv.appendChild(img);..
标签: javascript html css