本文介绍了为什么我得到TypeError:obj.addEventListener不是函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
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();
基本上,我正在使用firebug控制台并尝试在任何时候弹出警报点击一个标签。
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?
推荐答案
document.getElementsByTagName
返回。每个元素都有一个 addEventListener
函数,但该数组没有。
document.getElementsByTagName
returns a NodeList of DOM elements. Each element has an addEventListener
function, but the array doesn't have one.
循环遍历:
function showWinner (){
var aTags = document.getElementsByTagName("a");
for (var i=0;i<aTags.length;i++){
addEvent(aTags[i], 'click', alertWinner);
}
}
这篇关于为什么我得到TypeError:obj.addEventListener不是函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!