Can't set the title attribute while loading image in IE 7 and IE 8
I'm in the process of debugging a background image slideshow I wrote.
The flow of the script is that it loads the first image and displays it and then calls the preloadImages function which then loads the rest of the images at a preset interval.
preload_img
is a global variable defined at the start of my plugin ( var preload_img = 1;
) that keeps track of the current image number being preloaded and keeps its value like it should, but this value isn't being applied to the title attribute of the image.
// load the images in sequence one after another
function preloadImages()
{
clearInterval(interval_preload);
var div = '<div id="'+options.id_holder+preload_img+'" class="bg_img_holder"></div>';
$('#'+options.id_wrapper).append(div);
var img = new Image();
//alert("loading: " + options.img_path + images[preload_img].image + " " + preload_img);
$(img).load(function()
{
alert("loaded: " + $(this).attr('src') + " " + $(this).attr('title'));
$img_holder = $('#'+options.id_holder+$(this).attr('title'));
$img_holder.append(this)
.css({
'display': 'none',
'background-color': images[$(this).attr('title')].background,
'z-index': -500
})
.find('img')
.height($img_holder.width() * 0.5625);
}).attr({
'src': options.img_path + images[preload_img].image,
'title': preload_img
});
//if there's another image to load after this one
if(++preload_img < (images.length))
{
interval_preload = setInterval(preloadImages,1500);
}
}
Although preload_img
is defined while it loads the image ( the first alert which is commented out shows the correct value ) when the image is loaded the title is an empty string (the second, uncommented alert).
The issue doesn't present itself when the page is initially opened (open up browser, type in address, hit enter) but does every other time.
It's probably something small I've missed, but I've spent the last hour looking through this and am going crazy.
There's a really basic test case at: http://jsfiddle.net/72Sy6/4/ The alerts 开发者_如何学编程generate the expected data in all the browsers I've tested apart from IE7 which, has the expected data when the page is opened, but all other times does not.
I apologise in advance for the alert boxes, but that's the only way I know of debugging in IE7 :X
edit: Hadn't been experiencing errors in IE 8 with the slideshow, but this testcase shows the local variables as being similarly undefined.
For a reason I'm not entirely sure of, changing this:
var img = new Image();
$(img).load(function(){
//..
}).attr({
'src': options.img_path + images[preload_img].image,
'title': preload_img
});
to this:
var img = $('<img src="'+images[preload_img].image+'" title="'+images[preload_img].title+'" />');
$(img).load(function(){
//..
});
fixed the problem.
精彩评论