簡體   English   中英

返回結果前如何在圖像加載功能內部執行代碼?

[英]how to execute code inside of image onload function before returning the result?

我想返回在圖像加載功能內部執行的代碼。 代碼是:

function loadImage() {
  var data = null;
   var image = new Image();
   image.onload = function() {
     console.log("I am inside of image load function");
     data = "I am inside";
   }
   image.src="flower.jpg";
   console.log("I am outside of image load function");

   console.log(data);
   return data;
}

火狐控制台中的結果是:

I am outside of image load function
null
I am inside of image load function

我想要的是,上面的代碼應返回在圖像加載功能內部分配的數據值,即我希望返回的數據為“我在內部”。

I am inside of image load function
I am outside of image load function
I am inside

怎樣才能達到預期的效果?

要么

如何首先在image onload函數內部然后僅在函數外部執行代碼?

我猜上面的示例是其他示例的精簡示例?

不太清楚您要實現的目標,但是看一下代碼,您是否理解null為何會出現在哪里?

在控制台console.log(data)處,數據可能為空,因為圖像尚未完成加載。

當圖像加載時,您想發生什么?不能在卸載均勻處理程序中使它發生嗎?

暫無
暫無

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

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