问题描述
我遇到以下错误。
“未捕获的TypeError:无法读取未定义的属性'appendChild'”
我已经了解这种类型的错误的含义,但是我无法解释我的代码出了什么问题。
对于我的项目,这个想法是对卫星轨道的数值模拟,我将为此做一个大气模型。我正在为此使用THREE.js。
我体内有一个带有以下代码的html文件。 div-Container上的ID为“ container”,我以后想在一个函数中调用它。在我看来,该错误意味着我必须初始化div-Container。但是它是如何工作的?还是我做错了什么?
Blockquote
function init(){
scene = new THREE.Scene();
renderer = new THREE.Webglrenderer( { antialias: true } );
renderer.setSize( window.innerWidth,window.innerHeight );
//var container = document.getElementById('container');
document.body.appendChild(renderer.domElement);
document.getElementById("container").body.appendChild( renderer.domElement ); //here we have the error producing line
Blockquote
<body>
<link href="style.css" type="text/css" media="print" />
<div id="container"> //here is the div-container
<h2 id="titel">Numerische Simulation </h2>
<div id="sliderhoehe">
<input type="range" id="hoehe" name="hoehe" min="100" max="500" value="300" list="hoehewerte" step="20.0">
<label for="hoehe">Hoehe in km</label>
<datalist id="hoehewerte">
<option value="100" label="100"></option>
<option value="200" label="200"></option>
<option value="300" label="300"></option>
<option value="400" label="400"></option>
<option value="500" label="500"></option>
</datalist>
</div>
<div>
<input type="range" id="startv" name="startv" min="10000" max="200000" value="28000" list="startvwerte" step="1000">
<label for="startv">Geschwindikeit in km/h</label>
<datalist id="startvwerte">
<option value
</datalist>
</div>
<output for="hoehe" id="outputhoehe"></output>
<button id="stop">Stop</button>
<button id="start">Start</button>
<button id="reset">Reset</button>
</div>
我需要帮助。谢谢您的回答。
解决方法
我不确定您要尝试做什么,但是会引发该错误,因为您尝试访问容器元素上未定义的appendChild
属性上的body
。如果要将渲染器DOM元素附加到容器元素,只需删除.body
就可以直接将其添加到容器元素。也许因为有些body
元素而感到困惑,也许您认为它的含义类似于“元素的主体”。
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth,window.innerHeight );
document.getElementById("container").appendChild( renderer.domElement );
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r120/three.min.js"></script>
<body>
<link href="style.css" type="text/css" media="print" />
<div id="container"> //here is the div-container
<h2 id="titel">Numerische Simulation </h2>
</div>
</body>