问题
I have a code that works in JSFiddle but doesn't work when I save the HTML+JS locally and test it locally. I can't figure out what's wrong with the code. Here is my JSFiddle
http://jsfiddle.net/LLUAB/
And here is the actual code, not very long
<!doctype html>
<html>
<head>
<script type="text/javascript" language="Javascript">
function Composer(foobox) {
this.foobox = document.getElementById(foobox);
this.foobox.onkeydown = function(){window.alert("hello")};
}
var myComposer = new Composer("foo");
</script>
</head>
<body>
<textarea id="foo"></textarea>
</body>
</html>
回答1:
Because in JSFiddle your script is placed inside window.onLoad
event handler by default. While in your case getElementById()
method is unable to find not yet loaded element.
Put all your script right before closing </body>
tag and it will work:
<script type="text/javascript">
// ...
</script>
</body>
回答2:
It works in Fiddle because of onLoad
option specified here. The problem is that when new Composer
line is fired, there's no such element in the DOM yet. Wrap this line in DOMReady
handler - or move its invokation to the end of <body>
element.
回答3:
It's because your dom is not ready yet
function Composer(foobox) {
this.foobox = document.getElementById(foobox);
alert(this.foobox); --Prints null
this.foobox.onkeydown = function(){window.alert("hello")};
}
Working code here. http://jsfiddle.net/LLUAB/1/
来源:https://stackoverflow.com/questions/15572630/using-document-getelementbyid-inside-object-works-in-jsfiddle-typeerror-in-a