2013-08-16 91 views
0

我的情況是,我需要使用JavaScript來檢查圖像的大小,然後執行取決於其width.Here一段代碼是我的代碼觸發圖像的onload

 var width, height; 
     var img = new Image(); 
     img.src = "pool.jpg"; 
     img.onload = function() { 
      width = this.width; 
      height = this.height; 
      console.log(width); 
     } 
     console.log(width); 

     if (width > 0) { 
      console.log('in condition check'); 
      //Some code to be executed 
     } 
     //Some other code to be executed which cannot be put in the onload portion 

問題是img.onload部分只有在下面的代碼完成執行後纔有效。是否有任何方法可以觸發img.onload函數並以同步方式執行代碼。

回答

1

不,你不能讓你的代碼等待,直到外部任務(通常涉及服務器)完成執行。

把你的代碼中的回調(或在從回調調用的函數):

img.onload = function() { 
     width = this.width; 
     height = this.height; 
     console.log(width); 
     if (width > 0) { 
      console.log('in condition check'); 
      //Some code to be executed 
     } 
    } 

要構建JavaScript應用程序,你必須學會​​處理基於事件的編程,其中大部分代碼都是根據事件行事的,無論是用戶操作還是異步任務完成。

(技術上有一種方法,但不使用它)

+0

介意告訴我的方式:) – iJade

+0

它使用xmlhttprequest,但更完整和一個可怕的做法,沒有人使用,因爲當你能夠使用它,你有足夠的經驗來學習異步的方式,不阻止界面。您需要了解如何處理異步編程。 –

1

你需要等待回調,那麼你可以將結果傳遞給另一個功能:

var width, height; 
    var img = new Image(); 
    img.src = "http://kushsrivastava.files.wordpress.com/2012/11/test.gif"; 
    img.onload = function() { 
     width = this.width; 
     height = this.height; 
     console.log(width); 
     if (width > 0) { 
      console.log('in condition check'); 
      //Some code to be executed 
      haveFun(width); 
     } 
    } 
    var haveFun = function(w) { 
     console.log('Im having fun with ' + w); 
    } 

這裏有一個jsfiddle與一個小樣本。

+1

現在好了嗎?使用工具欄格式化爲代碼(或ctrl-k) –

+0

@dystroy真棒!謝謝你,不知道! –