[英]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? 如何在IE中的onload和onerror事件处理程序中确定触发事件的图像的图像src? 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. 在FF中工作,但在IE8中,它打印出$(event.target).attr('src')部分的undefined。 I thought jQuery was supposed to normalize the event object for IE so that it acted like other browsers?
我认为jQuery应该规范IE的事件对象,以便它像其他浏览器一样? I've tried a number of permutations but haven't been able to get anything to work in IE8.
我已尝试过多种排列,但未能在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. 无论如何,如果有人建议如何找出在IE中工作的onload和onerror事件处理程序中的图像src我会非常感激。 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
; 在Firefox和所有优秀的浏览器中,它是
.target
; in IE it's .srcElement
. 在IE中它是
.srcElement
。 Just insert this line before each append: 只需在每次追加之前插入此行:
var targetEl = event.target || event.srcElement;
Then change event.target
to: 然后将
event.target
更改为:
targetEl
OK, I figured it out. 好的,我明白了。
You have to use the currentTarget property of the event object not the target property - ie, 您必须使用事件对象的currentTarget属性而不是目标属性 - 即,
$("#log").append( $(event.currentTarget).attr('src') + ' WAS FOUND <br>');
works both in FF and IE8. 适用于FF和IE8。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.