JavaScript中EventListener报TypeError 迭代器/this/sq[i]未识别问题求助
问题根因
- 箭头函数的this指向问题:箭头函数不会创建自身的this上下文,其内部this继承自外层作用域,本案例中外层this指向window对象,调用
this.style自然会触发undefined相关的TypeError - 迭代器变量泄漏问题:用var声明的迭代变量i存在变量提升,且全局只有一个i,当事件触发时循环早已执行完毕,此时i的值已经等于sq.length,访问
sq[i]必然返回undefined
修复方案
方案1:替换箭头函数为普通函数(最简修复)
普通函数作为事件监听器回调时,this会自动绑定到触发事件的DOM元素上,代码如下:
var colors = ["rgb(255, 255, 0)","rgb(255, 0, 0)","rgb(255, 0, 255)","rgb(255, 120, 0)","rgb(255, 255, 255)","rgb(0, 0, 0)"]; const sq = document.querySelectorAll(".square"); const pick = "rgb(255, 0, 0)"; for(var i = 0; i < sq.length; i++){ sq[i].style.backgroundColor = colors[i]; // 把箭头函数换成普通function sq[i].addEventListener("click",function() { const clicked = this.style.backgroundColor; if(clicked === pick){ alert("right"); }else{ this.style.backgroundColor = "#232323" } }) }
方案2:保留箭头函数,用事件对象获取点击元素
如果需要保留箭头函数的外层this指向,可通过回调的事件参数target属性获取触发事件的DOM元素:
var colors = ["rgb(255, 255, 0)","rgb(255, 0, 0)","rgb(255, 0, 255)","rgb(255, 120, 0)","rgb(255, 255, 255)","rgb(0, 0, 0)"]; const sq = document.querySelectorAll(".square"); const pick = "rgb(255, 0, 0)"; for(var i = 0; i < sq.length; i++){ sq[i].style.backgroundColor = colors[i]; // 事件参数e sq[i].addEventListener("click",(e) => { const clicked = e.target.style.backgroundColor; if(clicked === pick){ alert("right"); }else{ e.target.style.backgroundColor = "#232323" } }) }
方案3:替换var为let修复迭代器作用域问题
如果你需要在回调中用到迭代变量i,把var i改为let i即可,let具备块级作用域,每次循环都会生成独立的i变量:
var colors = ["rgb(255, 255, 0)","rgb(255, 0, 0)","rgb(255, 0, 255)","rgb(255, 120, 0)","rgb(255, 255, 255)","rgb(0, 0, 0)"]; const sq = document.querySelectorAll(".square"); const pick = "rgb(255, 0, 0)"; // var改为let for(let i = 0; i < sq.length; i++){ sq[i].style.backgroundColor = colors[i]; sq[i].addEventListener("click",function() { // 此时访问sq[i]也不会返回undefined console.log('当前点击元素的索引',i) const clicked = this.style.backgroundColor; if(clicked === pick){ alert("right"); }else{ this.style.backgroundColor = "#232323" } }) }
内容的提问来源于stack exchange,提问作者Nikhil Chauhan
相关产品推荐
相关产品推荐

