<div id="a">ONE</div>
<div id="b">TWO</div>
<div id="c">THREE</div>
var el = document.getElementsByTagName("div");
for ( var i = 0; i < el.length; i++ ) (function(){
el.addEventListener("click",function(){
console.log(this.id + " " + this.innerHTML);
},false);
})(i);
给我错误“el.addEventListener不是函数”,有什么问题?
答案 0 :(得分:5)
el
是HTMLCollection,您忘记使用索引:
el[i].addEventListener("click",function(){...};
答案 1 :(得分:0)
您的代码中缺少[i]
(索引)(它必须是el[i]
),认为addEventListener
在IE版本中不起作用。要解决此问题,您可以执行以下操作:
function evt(elem,type,fn) { // element, event type, function
if ( elem.addEventListener ) {
elem.addEventListener(type,fn,false);
} else {
elem.attachEvent("on" + fn);
}
}