Img src 在 addEventListener 之后未定义

Img src is undefined after addEventListener

我想在鼠标悬停时将图片更改为 gif,并在鼠标移开时将其还原。但是 img src 在 onmouseout 之后保持未定义,但是它应该是可见的,因为 imgsrc 数组是一个全局变量

这是我的代码:

var list = document.querySelectorAll('span[data-oe-id] img');

var i;
var imgsrc=[];
for(i=0;i<3;i++)
{
    imgsrc[i] = list[i].src;
    list[i].addEventListener("mouseover",function(event)
    {
     console.log(imgsrc[i]); // Here it is undefined
     this.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
     });
    list[i].addEventListener("mouseout",function(event)
    {
      this.src=imgsrc[i]; // Here is the same thing
    });
}

您遇到的问题是 this。在事件侦听器中,this 表示 event 而不是调用事件的对象。

this.src更改为list[i].src

this.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";

list[i].src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";

改变 this.src=imgsrc[i];

list[i].src=imgsrc[i];

因为 let 是括号范围,更好的代码将是:

var list = document.querySelectorAll('span[data-oe-id] img');

for(let i=0; i<list.length; i++){
    let image = list[i];
    let src = image.src;

    image.addEventListener("mouseover",function(event){
     console.log(src); 
     image.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
    });
    image.addEventListener("mouseout",function(event){
      image.src=src; 
    });
}

检查一下并告诉我。