简体   繁体   中英

Javascript not declaring variables

i'm new to JavaScript i have this script and i want to declare a variable on a if but on document.write , returns nothing what am i doing wrong ?

<head>
    <script>
        (function () {
            setInterval(function () {
                var NetworkStatus = document.getElementById("status"),
                    isOnline = navigator.onLine;

                if (isOnline) {
                    NetworkStatus.innerHTML = "Online";
                    NetworkStatus.className = "online";
                    var person="John Doe";
                } else {
                    NetworkStatus.innerHTML = "Offline";
                    NetworkStatus.className = "offline";
                    var person="Santa Claus";
                }
            }, 100);
        })();
    </script>
</head>
<body>
    <h1 id="status"></h1>
    <script>
        document.write(person + "<br>");
    </script>
</body>

You are in IIFE . which creates its own scope

And that's where it stays

Do this :

window.person="Santa Claus";

Instead of what you're doing.

var sets the scope of the variable to the function it is declared within. You are trying to document.write it from outside that function, so it is out of scope and inaccessible.

Use window.person instead of var person .

该函数在100毫秒后执行,这意味着页面加载时person变量没有值。

It's just all wrong, why use an IIFE and a timeout when all you have to do is add the script in the tag at the end of the DOM.

Also, you're setting the innerHTML of the element, and using document.write, which will overwrite the document ?

<head>
    <title>I messed up</title>
</head>
<body>
     <h1 id="status"></h1>

    <script>
        var NetworkStatus = document.getElementById("status"),
            isOnline = navigator.onLine;

            if (isOnline) {
                var person = "John Doe";
                NetworkStatus.innerHTML = "Online " + person;
                NetworkStatus.className = "online";
            } else {
                var person = "Santa Claus";
                NetworkStatus.innerHTML = "Offline " + person;
                NetworkStatus.className = "offline";

            }
    </script>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM