javascript 无法读取 null 的属性“id” - JS 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31767354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:20:27  来源:igfitidea点击:

Cannot read property 'id' of null - JS error

javascripthtml

提问by Adam Freymiller

I have the following html code:

我有以下 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>

Yet in the console, I'm receiving an error when it reaches line 9 when it says "type of null does not exist", but clearly the id of the div must exist because I had it declared as an id in the body. How is this possible?

然而,在控制台中,当它到达第 9 行时,我收到一个错误,提示“null 类型不存在”,但显然 div 的 id 必须存在,因为我已将其声明为正文中的 id。这怎么可能?

回答by baao

Your html elements aren't loaded when the script is loaded and so don't exist at the time the javascript is executed. Changing the order of your code will solve the problem:

加载脚本时不会加载您的 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>

回答by Javi Muhrer

Your JS code is probably running before your HTML has fully rendered. To avoid this, don't run your code until the 'DOMContentLoaded' event has fired.

您的 JS 代码可能在 HTML 完全呈现之前正在运行。为避免这种情况,请在 'DOMContentLoaded' 事件触发之前不要运行您的代码。

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

回答by Ravi Sharma

Please load javascript after the whole html body won't get any error

请在整个 html body 不会出现任何错误后加载 javascript