从<div> </div> </li>中的数组生成<li>

时间:2014-11-13 15:34:12

标签: javascript

im geting 错误未捕获的TypeError:无法读取null的属性'appendChild',我不知道原因:

我尝试从数组中创建一个列表并将其显示在div

var options = [
    set0 = ['Option 1', 'Option 2'],
    set1 = ['First Option', 'Second Option', 'Third Option']
];

function makeUL(array) {
    // Create the list element:
    var list = document.createElement('ul');

    for (var i = 0; i < array.length; i++) {
        // Create the list item:
        var item = document.createElement('li');

        // Set its contents:
        item.appendChild(document.createTextNode(array[i]));

        // Add it to the list:
        list.appendChild(item);
    }

    // Finally, return the constructed list:
    return list;
}

// Add the contents of options[0] to #foo:
document.getElementById("foo").appendChild(makeUL(options[1]));
<div  id="foo"></div>

1 个答案:

答案 0 :(得分:0)

以下将解决您的问题

<html>
<head>
<script type="text/javascript">
var options = [
        set0 = ['Option 1','Option 2'],
        set1 = ['First Option','Second Option','Third Option']
                                    ];

        function makeUL(array) {
         // Create the list element:
        var list = document.createElement('ul');

        for(var i = 0; i < array.length; i++) {
         // Create the list item:
          var item = document.createElement('li');

         // Set its contents:
             item.appendChild(document.createTextNode(array[i]));

            // Add it to the list:
            list.appendChild(item);
                        }

            // Finally, return the constructed list:
                        return list;
                    }

            // Add the contents of options[0] to #foo:
            function DO()
            {
                document.getElementById("foo").appendChild(makeUL(options[1]));
            }
</script>
</head>
<body onload="DO()">
<div id="foo"></div>
</body>
</html>

发生此错误的原因是因为在加载HTML的Body之前执行了Javascript,因此它无法找到该div对象。如果您通过开发人员工具检查document.body将在函数执行之前为null。但是,如果你在身体加载时执行该功能,那么它将找到foo elem。