我想从中选择随机图片:


  http://9gag.com/top/all/index/page/1?view=json


为了正确显示它,我需要知道此图像的大小。

我使用YQL将此json的结果放入变量(称为源)中。

我用http替换https并删除每个反斜杠。

var it = $.parseJSON(source);
var total = it.count-1;
var random = Math.floor((Math.random()*total)+0);
var gagurl = it.items[random];
var gagurldecode = gagurl.replace('\\','');
gagurldecode = gagurldecode.replace('https','http'); //here is the url of the image


但我无法获取此图像的大小。

   var img = new Image();
   img.src = gagurldecode;


警报(img.height);什么也不返回。

如果我更换

img.src = gagurldecode;




img.src = 'http://d24w6bsrhbeh9d.cloudfront.net/photo/1777377_460s.jpg';


有用。

我做错了什么?
PS:对不起,我的英语!

最佳答案

这行是不必要的,因为在解析JSON时,斜杠会被转义:

var gagurldecode = gagurl.replace('\\','');


对于您的实际问题,在下载并检查图像之前,不会填充heightwidth。如果浏览器没有看到图像(在onload事件处理程序中),则异步完成此操作,但如果从缓存中检索图像,则可以同步完成,如您的硬编码示例:

img.onload = function() {
    alert(img.height);
}


这将每次都起作用。

关于javascript - 9gag解析JSON,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14063553/

10-12 12:28
查看更多