status.style is undefined

时间:2015-07-31 19:24:40

标签: javascript html

The browser’s console says:

TypeError: status.style is undefined, line 12
var status;
function output(msg,type="info"){
    status.innerHTML=msg;
    switch(type){
        case "info":
            status.style.background=undefined;
            break;
        case "warning":
            status.style.background="#cccc33";
            break;
        case "error":
            status.style.background="#ff0033";
            break;
    }
}
function init(){
    status=document.getElementById("status");
    output("Document loaded","error");
}
window.onload=init;
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" >
        <title>Drag and drop upload</title>
        <link href="css/style.css" rel="stylesheet" type="text/css" >
        <script src="js/script.js" type="text/javascript"> </script>
    </head>
    <body>
        <header>
            <h1>Drag & drop upload</h1>
        </header>
        <div id="main">
            <div id="status">Status</div>
            <div id="inner"> </div>
        </div>
        <footer>&copy; Copyright 2015</footer>

    </body>
</html>

I know this is so simple and basic but I got no other choice but to ask. As I tested I think this is a scope error. So what’s the problem?

1 个答案:

答案 0 :(得分:2)

You’re not actually referring to your status variable, but to window.status.

There are two possible solutions to this:

  • Simply don’t use status, but another variable name instead, or
  • Wrap your code in an IIFE like this: (function(){…}());

window.status is a special property: it has a WebIDL binding. In this case, this basically means that the value of the property is changed and updated secretly. In the case of window.status, whenever a value is assigned to it, it is turned into a string. That’s why console.log(status) yields the string

"[object HTMLDivElement]"

instead of the element

<div id="status">

And only HTML elements have the style property, not strings. That’s why status.style is undefined.

That’s not an issue if you access an undefined property of a defined value. That’s why status.innerHTML didn’t throw the error. But with status.style.background, you tried to access an undefined property of an undefined value.

If you use immediately invokable function expressions (IIFEs), you can use whichever variable names you want:

(function(){
  var status;
  // etc.
})();

window.status was used to set the status text of a window (back then, when browsers had status bars).