无法读取属性' id' null - JS错误

时间:2015-08-02 00:00:15

标签: javascript html

我有以下HTML代码:

<!DOCTYPE html>
<html>
<head>
<script>
    var array = ["one", "two", "three", "four"];
    for(i = 0; i<array.length; i++){
        alert(array[i]);
        var tmp = document.getElementById(array[i]);
        alert(tmp.id);
        alert(tmp.innerHTML);
        var to_append = tmp.innerHTML;
        array_inc.push(to_append);
        alert(array_inc);
        console.log(array_inc);
    }
</script>
</head>
<body>
    <div id = "one">1</div>
    <div id = "two">2</div>
    <div id = "three">3</div>
    <div id = "four">4</div>
</body>
</html>

然而在控制台中,当它到达第9行时我收到错误,并且#34; null类型不存在&#34;,但显然div的id必须存在,因为我有它被宣称为身体中的身份。这怎么可能?

3 个答案:

答案 0 :(得分:3)

加载脚本时,你的html元素没有被加载,因此在执行javascript时不存在。更改代码的顺序将解决问题:

<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <div id = "one">1</div>
    <div id = "two">2</div>
    <div id = "three">3</div>
    <div id = "four">4</div>
<script>
    var array = ["one", "two", "three", "four"];
    for(i = 0; i<array.length; i++){
        alert(array[i]);
        var tmp = document.getElementById(array[i]);
        alert(tmp.id);
        alert(tmp.innerHTML);
        var to_append = tmp.innerHTML;
        array_inc.push(to_append);
        alert(array_inc);
        console.log(array_inc);
    }
</script>
</body>
</html>

答案 1 :(得分:2)

您的JS代码可能在HTML完全呈现之前运行。为避免这种情况,请不要运行您的代码,直到“DOMContentLoaded”为止。事件已经解雇了。

<script>
    document.addEventListener("DOMContentLoaded", function(event) {
        // your code here
    });
</script>

答案 2 :(得分:0)

请在整个html主体赢得任何错误后加载javascript

相关问题