javascript 未捕获的类型错误:无法调用未定义的方法“addEventListener”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10189890/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:58:46  来源:igfitidea点击:

Uncaught TypeError: Cannot call method 'addEventListener' of undefined

javascriptdom

提问by Pasquale Sada

can't figure out where is the error in this code. Chrome debug console keep saying "Uncaught TypeError: Cannot call method 'addEventListener' of undefined" at line 31!

无法弄清楚此代码中的错误在哪里。Chrome 调试控制台在第 31 行一直说“未捕获的类型错误:无法调用未定义的方法‘addEventListener’”!

jewel.dom = (function() {

    var $ = Sizzle;

    function hasClass(el, clsName){

        var regex = new RegExp("(^|\s) + clsName + (\s|$)");
        return regex.test(el.className);
    }

    function addClass(el, clsName) {

        if (!hasClass(el,clsName)) {
            el.className += ""+ clsName;
        }
    }

    function removeClass (el, clsName) {

        var regex = new RegExp("(^|\s)" + clsName + "(\s|$)");
        el.className = el.className.replace(regex, " ");
    }

    function bind(element, event, handler) {

        if (typeof element == "string") {
            element = $(element)[0];
        }

        element.addEventListener(event, handler, false)
}

    return {
        $:$,
        hasClass : hasClass,
        addClass : addClass,
        removeClass : removeClass,
        bind : bind
    };
;}) ();

回答by Zhongjie Wu

In my case, this is caused by Evernote Clipper extension script. You will find "Evernote" in comment when you click to that script who throws out the error.

就我而言,这是由 Evernote Clipper 扩展脚本引起的。当您单击抛出错误的脚本时,您会在评论中找到“Evernote”。

回答by Alexander Pavlov

Could it be the case that your bindinvocation ends up with an undefinedelement? (e.g. you pass a selector that does not match any of the elements in your DOM)

您的bind调用是否会以undefinedelement? (例如,您传递的选择器与 DOM 中的任何元素都不匹配)

回答by d4rkpr1nc3

some browsers don't know what "addEventListener" is. Try this:

有些浏览器不知道“addEventListener”是什么。试试这个:

Element.prototype.setEvent = function(eventName, handler)
{
    if(document.addEventListener)
    {
        this.addEventListener(eventName, handler);
    }
    else
    {
        if(document.attachEvent)
        {
            this.attachEvent("on" + eventName, handler);
        }
    }
}
element.setEvent(eventName, handler);

The same goes for removeEventListener.

removeEventListener 也是如此。

Also, try to replace

另外,尝试更换

 element = $(element)[0];

with

 element = $("#" + element);

provided that string contains the id of the element, or

如果字符串包含元素的 id,或者

 element = $("." + element)[0];

if the string contains the className of the element.

如果字符串包含元素的 className。