简体   繁体   中英

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.com/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?

you need to declare the array first

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

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.

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 ] ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM