开发者

Javascript object not working in IE7

I have created the following javascript object dynamically (from 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.co开发者_如何学编程m/cnnbrk/statuses/121614678341320706", description: "This is the body of the tweat"}';
t_feed += ']';
twitterFeeds[0] = eval(t_feed);

This works fine in IE8+, but I get the following error in IE7:

SCRIPT5007: Unable to get value of the property 'thumbnail': object is null or undefined.

I get this when I try and access the thumbnail property like this:

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

Why does that fail in IE7 and is there a different way of defining a list or object that WILL work?


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

You may want to try parsing this string as JSON instead of using eval(), and then work from there.


you need to declare the array first

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


Your use of eval is unnecessary. Use the code directly:

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;

UPDATE: As @Quentin pointed out, it would be even cleaner to use PHP (assuming a valid class is created) and initialize a new Array with the instances in the array, then use json_encode on it. That way you don't have to worry about the syntax and escaping characters safely.

UPDATE 2: If you don't initialize twitterFeeds first it will also fail. Have you done that? If not, change to var twitterFeeds = [ t_feed ];

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜