在对象中使用document.getElementById(),实际上在JSFiddle,TypeError中工作。为什么? [英] Using document.getElementById() inside object, works in JSFiddle, TypeError in actual. Why?

查看:112
本文介绍了在对象中使用document.getElementById(),实际上在JSFiddle,TypeError中工作。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可在JSFiddle中工作的代码,但在本地保存HTML + JS并在本地进行测试时无法工作。我无法弄清楚代码有什么问题。这里是我的JSFiddle



http://jsfiddle.net/LLUAB /



这里是实际的代码,不是很长的

 <!doctype html> 
< html>
< head>
< script type =text / javascriptlanguage =Javascript>
函数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>


解决方案

因为在JSFiddle中,脚本放置在 window.onLoad 事件处理程序默认情况下。在您的情况下, getElementById()方法无法找到尚未加载的元素。

在关闭< / body> 标记之前,它会生效:

  < script type =text / javascript> 
// ...
< / script>
< / body>


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>

解决方案

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>

这篇关于在对象中使用document.getElementById(),实际上在JSFiddle,TypeError中工作。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆