Get the caller of the event from attachEvent

会有一股神秘感。 提交于 2019-12-08 05:19:12

问题


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...
    }

回答1:


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/




回答2:


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.



来源:https://stackoverflow.com/questions/11524762/get-the-caller-of-the-event-from-attachevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!