appendChild中的类型问题

Type Issue in appendChild

本文关键字:问题 类型 appendChild      更新时间:2023-09-26

我得到以下错误:

Type Issue
'undefined' is not an object (evaluating 'commands.appendChild')

下一行:

commands.appendChild(inputConfirm);

commands来自

var commands = document.forms['commands'];

这里没有错误,所以我相信commands是一个有效的表单对象。inputConfirm来自

var inputConfirm = document.createElement('input');

这里也没有错误,所以它应该也是有效的。我还设置了inputConfirm的一些属性,没有错误。

原因是什么?我笨…

编辑:脚本正在document.onload事件中执行。请看下面的确认答案

document.forms是一个包含页面表单的数组。数组索引必须是正数,因此document.forms[0]有效,document.forms['commands']无效。它引用了一个未定义的索引,所以结果在逻辑上是undefined。使用document.getElementById(),假设'commands'是id:

var form = document.getElementById('commands');
form.appendChild(...);

确保在执行此代码时元素存在(我的意思是,DOM已经准备好了)。如果您在<script>标记或<head>中的外部文件中有此代码,并且您没有将其包装在window.onloaddocument.DOMContentLoaded事件中,您会发现document.getElementById返回null

为了避免这种情况,如上所述,将代码放在任何这些事件的事件处理程序中,或者就在</body>结束标记之前。