简体   繁体   English

我是否可以保证在JavaScript事件处理程序中获得具有目标属性的事件对象?

[英]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. 就像标题说的那样,我很好奇是否可以保证在Javscript事件处理程序中获取事件对象。 The main reason I'm asking is that I've seen onClick event handlers that look like this. 我要问的主要原因是我看到了如下所示的onClick事件处理程序。

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

Which seems wrong to me, but I know Javascript can have minor variances across browsers. 这对我来说似乎是错误的,但是我知道Javascript在各个浏览器之间可能会有微小的差异。 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. 否。较早版本的Windows不会将事件参数传递给事件处理程序。 They have it in a global variable window.event and the target is in .srcElement . 他们在全局变量window.event拥有它,目标在.srcElement Other than that exception, you should always get an event structure. 除了那个例外,您应该始终获取一个事件结构。

A work-around for the older versions of IE is this: 较旧版本的IE的解决方法是:

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. 但是 ,对于较旧版本的IE, event对象是全局window对象的一部分。 In order to get the target in that case you would want window.event.srcElement , as there is no target . 在这种情况下,为了获得目标,您将需要window.event.srcElement ,因为没有target

More info here on the event object for IE. 有关IE event对象的更多信息,请参见此处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM