元素不更新内容

时间:2012-02-12 12:42:39

标签: javascript html navigator

以下是显示浏览器详细信息的JavaScript代码。它没有显示输出。请让我知道我在哪里做错了。

<html>
<head>
    <title></title>
    <script type="text/javascript">

        var txt;
        txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
        txt+= "<p>Browser Name: " + navigator.appName + "</p>";
        txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
        txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
        txt+= "<p>Platform: " + navigator.platform + "</p>";
        txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";

        document.getElementById("example").innerHTML=txt;

      </script>
</head>

<body>
    <p id="example"></p>
</body>
</html>

3 个答案:

答案 0 :(得分:3)

您在example div元素存在之前运行Javascript。稍后运行(=在文档末尾)。

答案 1 :(得分:2)

在您拥有example p之后保持代码处于正常状态,并且运行正常。

这样的东西会起作用。但是,您应该始终将您的JavaScript与HTML分开。

<!DOCTYPE html>
<html>
<head>
    <title></title>

</head>

<body>

    <p id="example"></p>
   <script type="text/javascript">

        var txt;
        txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
        txt+= "<p>Browser Name: " + navigator.appName + "</p>";
        txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
        txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
        txt+= "<p>Platform: " + navigator.platform + "</p>";
        txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";

        document.getElementById("example").innerHTML=txt;

      </script>
</body>
</html>

答案 2 :(得分:1)

您正在访问元素,但它尚不存在。原因是元素的定义晚于您的脚本。 null电话会getElementById TypeError,这会导致.innerHTML访问window.onload

使用window.onload = function() { var txt; // ... };

{{1}}
相关问题