You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 04:15:02