how to handle onLoad Event on img tag and others
how to handle onLoad
Event on img tag?
example:
$ ('img'). onload (function (e) {
alert ('image loaded' + $ (this), attr ('src开发者_开发问答'));
})
is like the imageLoader
and others tags like script, link, etc...
jQuery callback on image load (even when the image is cached)
$("img").one('load', function() {
// do stuff
}).each(function() {
if(this.complete) $(this).load();
});
Seems to work for me, and should fix the caveat with caching.
There's an example of how to do this right on the jQuery doc page for .load().
HTML:
<img src="book.png" alt="Book" id="book" />
Javascript:
$('#book').load(function() {
// Handler for .load() called.
});
And, there are a bunch of caveats to watch out for listed on that jQuery page too.
With images, if you want to assure that the load handler gets called, the load handler has to be set before the image can possibly be loaded. If you're constructing the image in code, that means you have to set the load handler before you set the .src
attribute. That's because, in some browsers, if the image is in the memory/disk cache, it will load immediately when you assign .src
and if you then subsequently set the .load()
handler, you will be too late (the image will already be loaded) and the .load()
handler will never be called.
I don't know how to guarantee that a jQuery-based .load() always gets called for an image that's in your page HTML because you can't assign the event handler until the object exists, but once the object it exits, it might already be loaded. You can use non-jQuery setting of an onload=xxx in the actual HTML though that is an older style of coding. Of course, you can always hook window.onload to know when all page images (and other resources) have been loaded.
jQuery has a load method, not onload. And your code should probably be:
$ ('img').load(function () {
alert('image loaded ' + this.src);
})
精彩评论