Following is the JavaScript code to reveal the Browser details. Its showing no output. Please let me know where I am doing wrong.

<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>
有帮助吗?

解决方案

Keep your code in after you have the example p and it will run fine.

Something like this will work. But, you should always separate your javascript from 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>

其他提示

You are running the Javascript before the example div element exists. Run it later (= at the end of the document).

You're accessing the element while it does not exist yet. The reason for this is that the element is defined later than your script. You'll get null for the getElementById call, which results in a TypeError for accessing .innerHTML.

Use window.onload:

window.onload = function() {
    var txt;
    // ...
};
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top