如何将Javascript数据打印到HTML DOM中?

时间:2015-06-10 00:40:05

标签: javascript html

我正在尝试将JS数据打印到HTML DOM中。 我无法打印出来。我做错了什么 ?

<!DOCTYPE html>
<html>

    <head>
        <title>JSON</title>
        <script type="text/javascript">
            // user is the property of obj1
            var obj1 = {
                user: "John",
                age: 26,
                country: "United States"
            };
            document.getElementById("results").innerHTML = obj1.user + "<hr>";
        </script>
    </head>

    <body>
        <div id="results"></div>         <---- Expected to see John HERE
    </body>

</html>

在我的控制台中

Uncaught TypeError: Cannot set property 'innerHTML' of null

Here is my JSFiddle

3 个答案:

答案 0 :(得分:1)

您收到错误的原因是您在head部分中指定了脚本,因此在创建id="results"的HTML元素之前执行脚本

不是在head部分导入脚本,而是在结束体标记</body>

之前导入它
    <body>
        <div id="results"></div>         <---- Expected to see John HERE
        <script type="text/javascript">
            // user is the property of obj1
            var obj1 = {
                user: "John",
                age: 26,
                country: "United States"
            };
            document.getElementById("results").innerHTML = obj1.user + "<hr>";
        </script>
    </body>

答案 1 :(得分:1)

在调用Javascript中的results时,未加载ID为document.getElementById("results").innerHTML = obj1.user + "<hr>";的div。

因此,window.onload可用于仅在加载文档时执行Javascript代码。

<!DOCTYPE html>
    <html>
    
        <head>
            <title>JSON</title>
            <script type="text/javascript">
                // user is the property of obj1
                window.onload = function() {
                    var obj1 = {
                        user: "John",
                        age: 26,
                        country: "United States"
                    };
                    document.getElementById("results").innerHTML = obj1.user + "<hr>";
                }
            </script>
        </head>
    
        <body>
            <div id="results"></div>         <---- Expected to see John HERE
        </body>
    
    </html>

另一种方法是将script标记(不在window.onload中,如在OP的帖子中)放在<div id="results"></div>后面,以便在执行JavaScript代码之前加载div。

答案 2 :(得分:1)

可能有多种方法可以解决这个问题,但我解决了这个问题 等待窗口加载:

 <PagerSettings 
Mode="NextPreviousFirstLast" 
PageButtonCount="5" 
PreviousPageText="Previous" 
NextPageText="Next" 
FirstPageText="First" 
LastPageText="Last" />