Get the caller of the event from attachEvent

2019-05-31 18:15发布

I am trying to do something simple: I have a bunch of Images which are being load through JS. I attach an event listener to the load event, and after the Image is being loaded, in the listener function I would like to get the calling Image and retrieve properties from it. Here is my code, simplified:

function loadImages() {
   for (var i = 0; i < arrDownloadQueueBasic.length; i++) {
                var path = arrDownloadQueueBasic[i].path;

                var img = new Image();
                img.type = arrDownloadQueueBasic[i].type;
                img.attachEvent(img, 'load', setBasicElement);
                img.src = path;
            }
   }

function setBasicElement(e) {
        var caller = e.target || e.srcElement;
        alert(caller); // THIS DOESNT WORK - RETURN NULL
        alert(caller.type) // OF COURSE THIS DOESNT WORK AS WELL...
    }

2条回答
狗以群分
2楼-- · 2019-05-31 18:37

There are a couple of things that you need to correct. First, the attachEvent method should not be used for browsers other than IE. You should structure your code to check if the method is implemented and then act accordingly like so:

if(img.addEventListener) {
    img.addEventListener('load', setBasicElement, false);
}
else if(img.attachEvent) {
    img.attachEvent('onload', setBasicElement);
}
else {
    img.onload = setBasicElement;
}

The other issue is that you need to prefix the event name with "on" when using attachEvent.

EDIT

You can get the caller by using the following code in the setBasicElement function:

var caller = e.target || e.srcElement || window.event.target || window.event.srcElement;

Here is a working example - http://jsfiddle.net/BMsXR/3/

查看更多
做自己的国王
3楼-- · 2019-05-31 18:48

Try this:

var caller = window.event ? window.event.srcElement : e.target;

If I remember rightly IE doesn't pass the event object as a parameter when you've used attachEvent(), but it has a global event object.

查看更多
登录 后发表回答