2013-02-18 134 views
0

所以我想讀取通過jQuery創建的img元素的高度和寬度。頁面加載和頁面刷新的價值差異

這是我試圖執行

$(document).ready(function() 
{ 
    $.ajax({ 
      url: 'res/script/getImage.php', 
      type: 'POST', 
      data: { 
       param : 'Load' 
      }, 
      success: function(result) 
      { 
       ImageArray = JSON.parse(result); 
       for(i=0; i<ImageArray.length; i++) 
       { 
         //Read the Image element and update to gallery 

         document.getElementById("gallery").innerHTML += ImageElement; 
         ImageArrayComplete[ImageCounter] = ImageArray[i].image; 
         UserArrayComplete[ImageCounter] = ImageArray[i].user; 

       } 

      //Create Canvas 
      $('#gallery img').each(function() { 
       console.log(this); 
       console.log('Width=' + this.width+ 'Height='+this.height); 
       createCanvas(this); 
      }); 

      } 
     }); 
}); 

console.log(this);輸出爲圖像,其是如預期的路徑的代碼。

但在初始頁面加載期間,對於寬度和高度,console.log('Width=' + this.width+ 'Height='+this.height);的輸出均爲0。

一旦刷新頁面,該值將重置爲實際寬度200。

沒有其他錯誤拋出併發生在Firefox和Chrome中。我在這裏錯過了什麼?

+0

頁面刷新意味着什麼?你按下'f5按鈕'來刷新它。 – 2013-02-18 04:36:54

+0

@Ravi是的,我按f5 – 2013-02-18 04:40:22

+0

'dataType:'json''丟失了,你在成功函數中得到了什麼'try.console.log(result)'。 – Jai 2013-02-18 04:41:09

回答

0

您確定img select是否具有高度和寬度值?

+0

如果屬性不存在,它們將是「undefined」而不是「0」 – matzahboy 2013-02-18 04:46:25

+0

是的,否則我不會當我刷新頁面時獲取值。該錯誤僅在初始頁面加載期間發生。 – 2013-02-18 04:49:02

+1

@在刷新頁面時發生錯誤,瀏覽器使用圖像的緩存副本,這意味着當您設置源時它即刻可用。在初始加載時,如果沒有緩存副本,唯一獲取寬度/高度的地方是將它們硬編碼爲實際的html標籤:'' – Norguard 2013-02-18 05:02:08

0

您的ImageElement對象未定義。試試這個:

變化

document.getElementById("gallery").innerHTML += ImageElement; 

$('<img/>').attr('src', ImageArray[i].image).appendTo($('#gallery')); 

this對象不具有heightwidth屬性。如果你想得到它的高度,使用:

console.log('Width=' + $(this).width() + 'Height=' + $(this).height()); 
+0

我已經定義了ImageElement。發帖太久了。它的一個簡短版本將是''ImageElement \t ='';'' – 2013-02-18 04:58:17

+0

我已經更新我的回答 – nvl 2013-02-18 04:59:57

+0

'this.height'將不起作用,您必須使用'$(this).height() ' – nvl 2013-02-18 05:00:44