2013-02-18 137 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