When the OnLoad event needs to be bound to the IMG, it is common to think of the usual method for event binding, as follows:
Copy Code code as follows:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title>img onload event Bindings (Error usage) </title>
<script type= ' Text/javascript ' >
Window.onload = function () {
var img = document.getElementById (' Imgid ');
Img.onload = function () {
Alert (1);
};
};
</script>
<body>
</body>
At this point, you will find that alert (1) did not execute, what is the reason? Especially in IE and FF browsers.
And when you use the jquery plug-in library, you will find that alert, in addition to the IE and opera browsers do not bounce out, other browsers are bouncing out, this is why?!
The main thing is that the Window.onload event is executed after the page DOM element is loaded, and includes the SRC load complete in the IMG image. Then the img.onload will not be carried out,
Because it is listening to the IMG src whether the load is complete.
So how do you bind an IMG image to the onload event? The specific code is as follows:
Copy Code code as follows:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title>img onload event bindings (correct usage) </title>
<script type= ' Text/javascript ' >
Window.onload = function () {
var img = document.getElementById (' Imgid ');
var src = img.getattribute (' src ');
Img.setattribute (' src ', ');
Img.onload = function () {
Alert (1);
};
Img.setattribute (' src ', src);
};
</script>
<body>
</body>
In this way, alert (1) is executed under each browser.
That is, after the page DOM element load completes, obtains the IMG's DOM object, obtains its SRC attribute, then sets its src to ' empty, then listens to the IMG of the OnLoad event, finally then sets the img src attribute.