Using document.getElementById() inside object, works in JSFiddle, TypeError in actual. Why?

荒凉一梦 提交于 2019-12-01 08:40:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!