简体   繁体   中英

Am I guaranteed to get an event object with a target property in a JavaScript event handler?

Just as the title says I'm curious if I'm guaranteed to get an event object inside of a Javscript event handler. The main reason I'm asking is that I've seen onClick event handlers that look like this.

function(e) {
    if(e && e.target) {
        //Code in here
    }
}

Which seems wrong to me, but I know Javascript can have minor variances across browsers. Is there some time at which it's appropriate to check for the event object? Or the event target? It seems like you'd have to have a target to fire off an event.

No. Older versions of windows don't pass the event argument to the event handler. They have it in a global variable window.event and the target is in .srcElement . Other than that exception, you should always get an event structure.

A work-around for the older versions of IE is this:

function(e) {
    if (!e) {
        e = window.event;
        e.target = e.srcElement;
    }
    // code that uses e here
}

But, usually, this is addressed at a higher level by the function that you use to install event handlers. For example:

// add event cross browser
function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(event, fn, false);
    } else {
        elem.attachEvent("on" + event, function() {
            // set the this pointer same as addEventListener when fn is called
            window.event.target = window.event.srcElement;
            return(fn.call(elem, window.event));   
        });
    }
}

Depending on the browser compatibility they are looking to achieve, this may be an acceptable solution. However , for older version of IE, the event object is a part of the global window object. In order to get the target in that case you would want window.event.srcElement , as there is no target .

More info here on the event object for IE.

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