简体   繁体   中英

Determine image src in onload and onerror event handlers in IE

How can I determine the image src of the image that triggered the event in the onload and onerror event handlers in IE? This example code I threw together:

<script language="javascript" type="text/javascript" src="jquery.js"></script>
<script language="javascript" type="text/javascript">
function loadImages() {
   var goodImage = new Image();
   var missingImage = new Image();

   $(goodImage).bind('load', function(event){
      $("#log").append( $(event.target).attr('src') + ' WAS FOUND <br>');
   });

   $(missingImage).bind('load', function(event){
      $("#log").append( $(event.target).attr('src') + ' WAS FOUND <br>' );
   });

   $(goodImage).bind('error', function(event){
      $("#log").append( $(event.target).attr('src') + ' IS MISSING <br>');
   });

   $(missingImage).bind('error', function(event){
      $("#log").append( $(event.target).attr('src') + ' IS MISSING <br>');
   });

  goodImage.src = 'GOOD-IMAGE.GIF'; // this image exists
  missingImage.src = 'MISSING-IMAGE.GIF'; // this image doesn't exist
}

</script>
</head>
<body onload="loadImages();">
<div id="log"></div>

works in FF but in IE8 it prints out undefined for the $(event.target).attr('src') part. I thought jQuery was supposed to normalize the event object for IE so that it acted like other browsers? I've tried a number of permutations but haven't been able to get anything to work in IE8.

Anyway if anyone has a suggestion on how to figure out the image src in the onload and onerror event handlers that works in IE I would really appreciate it. Or even how to figure out after the images have loaded which have loaded and which haven't (but not graphically - I need to generate an array containing the filenames of the images that didn't load). Thanks!

In Firefox and all good browsers it's .target ; in IE it's .srcElement . Just insert this line before each append:

var targetEl = event.target || event.srcElement;

Then change event.target to:

targetEl

OK, I figured it out.

You have to use the currentTarget property of the event object not the target property - ie,

  $("#log").append( $(event.currentTarget).attr('src') + ' WAS FOUND <br>');

works both in FF and IE8.

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