我需要使用人种来填充表单中的下拉列表框。我相信我已经正确完成了但是我收到一条错误,上面写着错误:无法获取未定义或空引用的属性'appendChild'
我做错了什么?
HTML:
<!DOCTYPE html />
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="TheCSS.css" />
<style type="text/css">
.style1 {
height: 26px;
}
</style>
</head>
<body>
<script type="text/javascript" src="C:\Users\Marc\Desktop\JavaScript Projects\TheJavaScript.js"></script>
<center>
<table class="style1">
<tr>
<td colspan="4">
<center>
<h1><b>New Hire Form</b></h1>
</center>
</td>
</tr>
<tr>
<td id="subHeader" colspan="4"></td>
</tr>
<tr>
<td class="style3">First Name</td>
<td class="style2">
<input type="text" id="FirstName" onchange="return LastName_onchange()" />
</td>
<td class="style4">Last Name</td>
<td>
<input id="LastName" type="text" onchange="return FirstName_onchange()" />
</td>
</tr>
<tr>
<td class="style1">Sex</td>
<td class="style1">Male
<input id="Radio1" checked="true" name="R1" type="radio" value="M" /> Female
<input id="Radio1" checked="true" name="R1" type="radio" value="F" />
</td>
<td class="style1">Race</td>
<td class="style1">
<select id="RaceDropDown" name="D1"></select>
</td>
</tr>
<tr>
<td class="style3"> </td>
<td class="style2"> </td>
<td class="style4">
<input type="button" id="myButt" value="Submit Entry" onclick="return myButt_onclick()" />
</td>
<td> </td>
</tr>
</table>
</center>
</body>
</html>
的JavaScript:
var select = document.getElementById('RaceDropDown');
var options = ["Asian", "Black"];
var i;
for (i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
function LastName_onchange() {
var LastName = document.getElementById('LastName').value;
var FirstName = document.getElementById('FirstName').value;
document.getElementById('subHeader').textContent = FirstName + " " + LastName + " " + new Date();
}
function FirstName_onchange() {
var LastName = document.getElementById('LastName').value;
var FirstName = document.getElementById('FirstName').value;
document.getElementById('subHeader').textContent = FirstName + " " + LastName + " " + new Date();
}
CSS:
#subHeader
{
text-align: right;
}
答案 0 :(得分:3)
改变这个:
for (i = 0; i <= options.length; i++)
到
for (i = 0; i < options.length; i++)
只需要<
。不是<=
答案 1 :(得分:1)
正如我的评论中所提到的,应在创建元素后调用脚本。如果没有,脚本会抛出错误,因为它找不到要添加select
的{{1}}元素。
请创建一个用于填充下拉列表的功能,并将其称为options
,如下所示:
onload
另外,在for循环中function popDropDown() {
var select = document.getElementById('RaceDropDown');
var options = ["Asian", "Black", "White"];
var i;
for (i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
window.onload = popDropDown;
就足够了i < options.length
。