簡體   English   中英

在 addEventListener 之后,img src 未定義

[英]Img src is undefined after addEventListener

我想在鼠標懸停時將圖片更改為 gif,並在鼠標移出時將其還原。 但是在onmouseout之后img src保持未定義,但是它應該是可見的,因為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而不是調用事件的 object。

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 是括號 scope,所以更好的代碼是:

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; 
    });
}

檢查一下,讓我知道。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM