-1

不断收到此错误:Uncaught TypeError: Cannot call method 'appendChild' of null main.js:24 makingMySelect main.js:24 (anonymous function) 这是代码:

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 ();
4

1 回答 1

2

在执行此部分之前使用检查:

if (selectLi)
    selectLi.appendChild(makeSelect);

所以,这检查是否selectLi已经很好了。然后添加东西。另外,你确定有一个带有IDas的元素select吗?不要混淆标记名。:)


工作 HTML 代码

问题是您没有带有idof的元素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>
于 2013-06-13T14:54:52.763 回答