简体   繁体   English

TypeError:elem.addEventListener不是一个函数

[英]TypeError: elem.addEventListener is not a function

At some place I have a code elem.addEventListener(event, listener, false); 在某个地方,我有一个代码elem.addEventListener(event, listener, false);

The above code works for 上面的代码适用于

this.buttonBar = doc.getElementsByClassName("wmd-button-bar" + postfix)[0]

But when I change to 但是当我改变为

this.buttonBar = $('.wmd-button-bar').first();

It does not work. 这是行不通的。 In whole html code I have only one wmd-button-bar class. 在整个html代码中,我只有一个wmd-button-bar类。

The reason why it's not working is because $('.wmd-button-bar').first(); 它不起作用的原因是因为$('.wmd-button-bar').first(); (which equals to $('.wmd-button-bar').eq(0) ) returns the first jQuery wrapped instance. (等于$('.wmd-button-bar').eq(0) )返回第一个jQuery包装的实例。

Therefore you should use jQuery's own API for adding the listener. 因此,您应该使用jQuery自己的API来添加侦听器。

However, if you want to receive a first DOM element from collection, you should use 但是,如果要从集合中接收第一个DOM元素,则应使用

$('.wmd-button-bar').get(0);

This will return first element from the jQuery wrapped collection as a DOM element. 这将从jQuery包装的集合中返回第一个元素作为DOM元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM