javascript 无法将属性“innerHTML”设置为 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18239430/
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-27 11:09:57  来源:igfitidea点击:

Cannot set property 'innerHTML' of null

javascriptonloadinnerhtml

提问by Joshua W

Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null? I thought I understood innerHTML and had it working before.

为什么我会收到错误或 Uncaught TypeError: Cannot set property 'innerHTML' of null?我以为我理解了 innerHTML 并且以前使用过它。

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>

<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>

</head>

<body>
<div id="hello"></div>
</body>
</html>

回答by Erik Godard

You have to place the hellodiv before the script, so that it exists when the script is loaded.

您必须将hellodiv 放在脚本之前,以便在加载脚本时它存在。

回答by RBT

Let us first try to understand the root cause as to why it is happening in first place.

让我们首先尝试了解其发生的根本原因。

Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?

为什么我会收到错误或 Uncaught TypeError: Cannot set property 'innerHTML' of null?

The browser always loads the entire HTML DOM from top to bottom. Any JavaScript code written inside the scripttags (present in headsection of your HTML file) gets executed by the browser rendering engine even before your whole DOM (various HTML element tags present within body tag) is loaded. The scripts present in headtag are trying to access an element having id helloeven before it has actually been rendered in the DOM. So obviously, JavaScript failed to see the element and hence you end up seeing the null reference error.

浏览器总是从上到下加载整个 HTML DOM。甚至在加载整个 DOM(body 标签中存在的各种 HTML 元素标签)之前,浏览器渲染引擎都会执行script标记内编写的任何 JavaScript 代码(存在于headHTML 文件的部分)。head标签中的脚本试图访问具有 id 的元素,hello甚至在它实际在 DOM 中呈现之前。很明显,JavaScript 无法看到该元素,因此您最终会看到空引用错误。

How can you make it work as before?

你怎么能让它像以前一样工作?

You want to show the "hi" message on the page as soon as the user lands on your page for the first time. So you need to hook up your code at a point when you are completely sure of the fact that DOM is fully loaded and the helloid element is accessible/available. It is achievable in two ways:

您希望在用户第一次登陆您的页面时立即在页面上显示“嗨”消息。因此,当您完全确定 DOM 已完全加载并且helloid 元素可访问/可用时,您需要连接代码。它可以通过两种方式实现:

  1. Reorder your scripts: This way your scripts get fired only after the DOM containing your helloid element is already loaded. You can achieve it by simply moving the script tag after all the DOM elements i.e. at the bottom where bodytag is ending. Since rendering happens from top to bottom so your scripts get executed in the end and you face no error.
  1. 重新排序你的脚本:这样你的脚本只有在包含你的helloid 元素的 DOM已经加载后才会被触发。您可以通过简单地在所有 DOM 元素之后移动脚本标签来实现它,即在body标签结束的底部。由于渲染是从上到下进行的,因此您的脚本最终会被执行并且您不会遇到任何错误。

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Untitled Document</title>
    </head>
    
    <body>
    <div id="hello"></div>
    
    <script type ="text/javascript">
        what();
        function what(){
            document.getElementById('hello').innerHTML = 'hi';
        };
    </script>
    </body>
    </html>

  1. Use event hooking: Browser's rendering engine provides an event based hook through window.onloadevent which gives you the hint that browser has finished loading the DOM. So by the time when this event gets fired, you can be rest assured that your element with helloid already loaded in the DOM and any JavaScript fired thereafter which tries to access this element will not fail. So you do something like below code snippet. Please note that in this case, your script works even though it is present at the top of your HTML documentinside the headtag.
  1. 使用事件挂钩:浏览器的渲染引擎通过window.onload事件提供了一个基于事件的挂钩,它会提示您浏览器已完成加载 DOM。因此,当这个事件被触发时,你可以放心,你的helloid元素已经加载到 DOM 中,之后任何试图访问这个元素的 JavaScript 都不会失败。所以你做一些类似下面的代码片段。请注意,在这种情况下,即使您的脚本位于head标记内HTML 文档的顶部,它也能正常工作

<!DOCTYPE HTML>
        <html>
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Untitled Document</title>
        <script type ="text/javascript">
            window.onload = function() {
            what();
            function what(){
                document.getElementById('hello').innerHTML = 'hi';
            };
        }
        </script>
        </head>
        
        <body>
        <div id="hello"></div>
        </body>
        </html>

回答by Colyn1337

You could tell javascript to perform the action "onload"... Try with this:

您可以告诉 javascript 执行“onload”操作...试试这个:

<script type ="text/javascript">
window.onload = function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>

回答by RIYAJ KHAN

Just put your JS in window.onload

把你的JS放进去 window.onload

window.onload = function() {

        what();

        function what() {
            document.getElementById('hello').innerHTML = 'hi';
        };

    }

回答by JT Nolan

Javascript looks good. Try to run it after the the div has loaded. Try to run only when the document is ready. $(document).readyin jquery.

Javascript 看起来不错。尝试在 div 加载后运行它。尝试仅在文档准备好时运行。$(document).ready在jQuery中。

回答by user6175882

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>

</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = '<p>hi</p>';
    };
</script>  
</body>
</html>

回答by user5323957

The JavaScript Part Need To Run Once Page Is Loaded Therefor It Is Advised To Place JavaScript Script At The End Of Body Tag

JavaScript 部分需要在页面加载后运行,因此建议将 JavaScript 脚本放在 Body 标签的末尾

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>

</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>  
</body>
</html>

回答by Pines Tran

The root cause is: HTML on a page have to loaded before javascript code. Resolving in 2 ways:

根本原因是:页面上的 HTML 必须在 javascript 代码之前加载。2种方式解决:

1) Allow HTML load before the js code.

1) 允许在 js 代码之前加载 HTML。

<script type ="text/javascript">
    window.onload = function what(){
        document.getElementById('hello').innerHTML = 'hi';
    }
</script>

//or set time out like this:
<script type ="text/javascript">
    setTimeout(function(){
       what();
       function what(){
          document.getElementById('hello').innerHTML = 'hi';
       };
    }, 50);
    //NOTE: 50 is milisecond.
</script>

2) Move js code under HTML code

2) 将 js 代码移到 HTML 代码下

<div id="hello"></div>
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>

回答by Eddy

You could try using the setTimeout method to make sure your html loads first.

您可以尝试使用 setTimeout 方法来确保您的 html 首先加载。

回答by Eddy

Here Is my snippet try it. I hope it will helpfull for u.

这是我的片段尝试一下。我希望它对你有帮助。

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>

<body>
  
<div id="hello"></div>
  
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>
</body>
</html>