Javascript对象在IE7中不起作用

时间:2011-10-05 18:03:45

标签: javascript

我已经动态创建了以下javascript对象(来自PHP):

var t_feed = '';
t_feed += '[';
t_feed += '{name: "Tom Thumb", thumbnail: "images/Tom_Thumb.jpg", link: "http://twitter.com/cnnbrk/statuses/121630545879900161", description: "This is the body of the tweat"},';
t_feed += '{name: "Tom Thumb", thumbnail: "images/Tom_Thumb.jpg", link: "http://twitter.com/cnnbrk/statuses/121622456363524097", description: "This is the body of the tweat"},';
t_feed += '{name: "Tom Thumb", thumbnail: "images/Tom_Thumb.jpg", link: "http://twitter.com/cnnbrk/statuses/121614678341320706", description: "This is the body of the tweat"}';
t_feed += ']';
twitterFeeds[0] = eval(t_feed);

这在IE8 +中运行良好,但我在IE7中收到以下错误:

  

SCRIPT5007:无法获取属性“缩略图”的值:对象是   null或undefined。

当我尝试访问缩略图属性时,我得到了这个:

$.each(twitterFeeds[id], function(i,item){
    alert(item.thumbnail);
});

为什么在IE7中失败并且有一种不同的方式来定义一个可行的列表或对象?

3 个答案:

答案 0 :(得分:2)

你需要先声明数组

var twitterFeeds = []; // declaration
twitterFeeds[0] = eval(t_feed);
alert(twitterFeeds);

答案 1 :(得分:2)

As a general rule, if you’re using eval() there’s probably something wrong with your design.

您可能希望尝试将此字符串解析为JSON而不是使用eval(),然后从那里开始工作。

答案 2 :(得分:1)

您无需使用eval。直接使用代码:

var t_feed = [
 {name: "Tom Thumb", thumbnail: "images/Tom_Thumb.jpg", link: "http://twitter.com/cnnbrk/statuses/121630545879900161", description: "This is the body of the tweat"},
 {name: "Tom Thumb", thumbnail: "images/Tom_Thumb.jpg", link: "http://twitter.com/cnnbrk/statuses/121622456363524097", description: "This is the body of the tweat"},
 {name: "Tom Thumb", thumbnail: "images/Tom_Thumb.jpg", link: "http://twitter.com/cnnbrk/statuses/121614678341320706", description: "This is the body of the tweat"}
];
twitterFeeds[0] = t_feed;

更新:正如@Quentin指出的那样,使用PHP会更加清晰(假设创建了一个有效的类)并使用数组中的实例初始化一个新数组,然后使用json_encode它。这样您就不必担心语法和安全转义字符。

更新2:如果您没有首先初始化twitterFeeds,它也将失败。你做到了吗?如果没有,请更改为var twitterFeeds = [ t_feed ];

相关问题