javascript 对象 [object Object] 没有方法 'addEventListener'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7679472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Object [object Object] has no method 'addEventListener'
提问by Lazer
If I include the latest version of jQuery from the jquery.com site on my page:
如果我在我的页面上包含来自 jquery.com 站点的最新版本的 jQuery:
<script src="http://code.jquery.com/jquery-latest.js"></script>
then line 3 of the following code (pscript.js):
然后是以下代码的第 3 行 (pscript.js):
function init() {
$("textbox").focus();
$("textbox").addEventListener("keyup", _keytext, false); // line 3
$("textbox").addEventListener("blur", _save, false);
...
produces the following error:
产生以下错误:
pscript.js:3 Uncaught TypeError: Object [object Object] has no method 'addEventListener'
pscript.js:3 Uncaught TypeError: Object [object Object] 没有方法“addEventListener”
I confirmed that this error goes away if the jquery script is not included. What am I doing wrong? How do I include jquery without the error?
我确认如果不包含 jquery 脚本,这个错误就会消失。我究竟做错了什么?如何在没有错误的情况下包含 jquery?
回答by Joseph Marikle
Try each
to access each node directly:
尝试each
直接访问每个节点:
$("textbox").each(function(){
this.addEventListener("keyup",_keytext,false);
});
or use a jQuery event handler attachment method:
或使用 jQuery 事件处理程序附件方法:
$("textbox").bind("keyup",_keytext);
By default, $
is defined by jQuery to return a jQuery object, a node collection (with jQuery methods), rather than a single node. As such, the return value has no addEventListener
method. bind
(and on
) are used with jQuery, rather than addEventListener
.
默认情况下,$
由 jQuery 定义返回一个jQuery 对象,一个节点集合(使用 jQuery 方法),而不是单个节点。因此,返回值没有addEventListener
方法。bind
(和on
) 与 jQuery 一起使用,而不是addEventListener
.
If you define your own $
(or use another library that does so), you can revert the definition of $
so that jQuery will coexist with other librariesby calling jQuery.noConflict()
. Alternatively, include the other library or define $
after including jQuery, so jQuery's definition will be overwritten.
如果你定义自己$
(或使用这样做的另一个库),可以恢复的定义$
,使jQuery将与其他库共存调用jQuery.noConflict()
。或者,包含其他库或$
在包含 jQuery 后定义,这样 jQuery 的定义将被覆盖。
回答by Lazer
The actual problem was that I had defined $
function like this
实际的问题是我已经定义了这样的$
函数
function $(id) {
return document.getElementById(id);
}
Now since jQuery has its own definition of $
, my definition was getting overridden, and hence the unexpected error.
现在,由于 jQuery 有自己的 定义$
,我的定义被覆盖了,因此出现了意外错误。
回答by Dennis
In order to grab your element, you need to provide the selector #textarea
otherwise, jQuery will try to select all elements with the textarea tag.
为了获取您的元素,您需要提供选择器,#textarea
否则 jQuery 将尝试选择所有带有 textarea 标签的元素。