javascript 为什么我收到 TypeError: obj.addEventListener is not a function?

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

why am I getting TypeError: obj.addEventListener is not a function?

javascriptjavascript-events

提问by max7

Here's my code:

这是我的代码:

function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener(type, fn, false);
}

function alertWinner(){
    alert("You may be a winner!");
}

function showWinner (){
    var aTag = document.getElementsByTagName("a");
    addEvent(aTag, 'click', alertWinner);
}

showWinner();

Basically, I'm working in the firebug console and trying to get an alert to pop up when any a tag is clicked.

基本上,我在 firebug 控制台中工作,并试图在单击任何标签时弹出警报。

I can't see the problem that results in this not working and giving me the error stated in my questions title (viewed in firebug). Anybody?

我看不到导致这不起作用的问题,并给我问题标题中所述的错误(在萤火虫中查看)。有人吗?

回答by Matt Zeunert

document.getElementsByTagNamereturns a NodeListof DOM elements. Each element has an addEventListenerfunction, but the array doesn't have one.

document.getElementsByTagName返回一个DOM 元素的NodeList。每个元素都有一个addEventListener函数,但数组没有一个。

Loop over it:

循环它:

function showWinner (){
    var aTags = document.getElementsByTagName("a");
    for (var i=0;i<aTags.length;i++){
        addEvent(aTags[i], 'click', alertWinner);
    }
}

回答by Sebas

aTagis an instance of DOMNodeList, not from DOMElement.

aTag是 的一个实例DOMNodeList,而不是来自DOMElement

You could do this instead:

你可以这样做:

var aTags = document.getElementsByTagName("a");
var aTag = aTags[0];

But obviously this approach presents a flaw, in that there might be more than one aelement returned. You should use a different selector that returns only one element, if possible.

但显然这种方法存在一个缺陷,即可能a返回多个元素。如果可能,您应该使用仅返回一个元素的不同选择器。

回答by Jason Lydon

Not sure why, but I got addEvent is not definedin Firefox. I couldn't even find addEvent()on MDN. I had to use this:

不知道为什么,但我进入addEvent is not defined了 Firefox。我什至addEvent()在 MDN 上都找不到。我不得不使用这个:

function showWinner (){
    var aTags = document.getElementsByTagName("a");
    for (var i=0;i<aTags.length;i++){
        // addEvent(aTags[i], 'click', alertWinner);
        aTags[i].addEventListener("click", alertWinner);
    }
}