继续收到此错误: 未捕获的TypeError:无法调用方法' appendChild' of null main.js:24 makeMySelect main.js:24 (匿名功能) 这是代码:
window.addEventListener("DOMContentLoaded", function(){
function $(x){
var myElements = document.getElementById(x);
return myElements;
}
// create select field element and populate with options
function makingMySelect (){
var formTag = document.getElementsByTagName("form");// array
var selectLi = $("select");
var makeSelect = document.createElement("select");
makeSelect.setAttribute("id","peopleGoing");
for(i=0,j=reservePeopleGoing.length;i<j;i++){
var makeOption = document.createElement("option");
var optText = reservePeopleGoing[i];
makeOption.setAttribute("value", optText);
makeOption.innerHTML = optText;
makeSelect.appendChild(makeOption);
}
selectLi.appendChild(makeSelect);
}
var reservePeopleGoing = ["1","2","3","4","5"];
var placeToGo = ["Astrada's","AppleBees","Chili's","Outback","O'Charleys"]
makingMySelect ();
答案 0 :(得分:2)
在执行此部分之前使用检查:
if (selectLi)
selectLi.appendChild(makeSelect);
因此,这会检查selectLi
是否已经很好。然后添加东西。另外,您确定ID
的元素为select
吗?不要在标记名之间混淆。 :)
使用HTML代码
问题是您没有id
select
的元素。所以,我刚刚添加了这段代码:
<div id="select"></div>
注册链接后,它的工作原理。请享用。完整代码供您参考。
<!doctype html>
<html manifest="/cache.manifest">
<head>
<meta charset="utf-8" />
<meta keywords="Reserve,resteraunt,hotel" />
<meta description="This app will let you reserve a spot at your favorite location" />
<meta name="robots" content="index,follow" />
<meta name="viewport" content="user-scalable=no, width=device-width" />
<meta name="HandheldFriendly" content="True" />
<meta name="MobileOptimized" content="320" />
<meta name="viewport" content="target-densitydpi-dpi" />
<link href="css/style.css" rel="stylesheet"/>
<title>Make My Reservation</title>
</head>
<body>
<header>
<div class="container">
<h1>My Reservation App</h1>
<p>This app will let you make a reservation! </p>
</div>
</header>
<h3>Ready?</h3>
<p><a href= "addItem.html">Add A Reservation</a></p>
<div id="select"></div>
</body>
<footer>
<img src="img/Reservation_app_img.jpg"width= "100" height="100" title="Reservation Logo" />
<p1>6-3-2013, Brian Stacks</p1>
</footer>
<script type="text/javascript" src="js/main.js"></script>
</html>