2012-11-27 115 views
0

我使用javascript来输出图像,在FF和Chrome中一切正常,但在IE中只有第一张图像在第一次加载页面时被追加刷新页面后,所有图像都会被添加。

Javascript来输出图像:

$.getJSON("php/v.php?"+Math.random(),function(data){    
       $.each(data,function(l){ 
         if(data[l]['s']==1){     
          $("#img"+(l+1)).append("<img src='"+data[l]['img']+"' />"); 
         }     
        }); 
     }); 

从从v.php IE9开发工具响应:

[{"img":"https:\/\/www.example.com\/example.jpg","s":"1"},{"img":"https:\/\/www.example.com\/example.jpg","s":"1"},{"img":"https:\/\/www.example.com\/example.jpg","s":"1"}] 

所以问题应该已经引起各个元素,而不是的getJSON。 在stackoverflow上发现很多类似的问题,但没有那样的 (http://stackoverflow.com/questions/7785138/each-method-only-applies-to-first-element-in-ie,http://stackoverflow.com/questions/4664190/javascript-each-loop-over-json-only-getting-first-element),但在我的情况下,问题也发生在IE9中。

+0

你可以尝试把你的Javascript中的$(document)。就绪(函数(){} –

回答

0

我觉得你可以在本地浏览器调试首先是这样的:

var data= [{},{},{}];//your data 

$.each(data,function(l){ 
    if(data[l]['s']==1){     
     $("#img"+(l+1)).append("<img src='"+data[l]['img']+"' />"); 
    }     
}); 

//and this way 
for(var i=0,l=data.length; i<l; i++){ 
    if(data[l]['s']==1){     
     $("#img"+(l+1)).append("<img src='"+data[l]['img']+"' />"); 
    } 
} 

//and the third way 
for(var i=0,l=data.length; i<l; i++){ 
    if(data[l]['s']==1){ 
     var img = new Image(); 
     img.onload = function(){ 
      var id = '#img'+(l+1); 
      $(id).append(this); 
     } 
     img.src = data[l]['img']; 
    } 
} 
+0

更改我的代码以使用第二种调试方式,现在它正常工作,很奇怪。 – SuperKingTurban

0

您的JSON中存在语法错误。第二个URL有两个收“行情

+0

这只是编辑出错的一个错误,修复了它 – SuperKingTurban

相关问题