如何在内联添加事件侦听器时获取事件对象 [英] How to get the event object when event listener is added inline

查看:55
本文介绍了如何在内联添加事件侦听器时获取事件对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在内联添加事件处理程序,使用 onclick 元素的attrubute,如下所示:

Suppose I add the event handler inline,use the onclick attrubute of the element like this:

<input type="button" value="Submit" onclick='buttonClick()' />

然后这是我的经纪人:

<script type="text/javascript">
    window.buttonClick=function(e){
        e=e||window.event;
        alert(e.type);
        return false;
    }
</script>

现在我想知道如何获取事件对象?由于上面的代码会抛出错误: e未定义

Now I want to know how to get the event object? Since the above code will throw error: e is undefined.

推荐答案

那个在内联事件中使用事件变量。

That's not using the event variable in the inline event.

在这种情况下 buttonClick 是一个来自内联事件的函数,名为;被调用的函数没有神奇的访问事件变量( window.event 是一个IE功能)。此外,在帖子中,使用0参数调用 buttonClick ,因此 e 将始终评估为未定义。

In this case buttonClick is a function called from the inline event; the called function does not have magical access to the event variable (window.event is an IE feature). Furthermore, in the post, buttonClick was called with 0 arguments so e will always evaluate to undefined.

在任何情况下,与以下内容进行比较,这些内容将作为访问特殊的事件变量是从内联事件本身和事件对象完成的然后传递给真实事件处理函数:

In any case, compare with the following which will work as access to the special event variable is done from the inline event itself and the event object is then passed off to the "real" event handler function:

<input type="button" value="Submit"
       onclick="buttonClick(window.event||event)" />

<script type="text/javascript">
    function buttonClick(e) {
        alert(e.type);
        return false;
    }
</script>

(我建议使用jQuery或其他库来简化统一事件访问,但这是另一个故事。 。)

(I would recommend using jQuery or another library to make uniform event access easier, but that's another story ..)

注意 window.event || event 是一个肮脏的小技巧:

Note that window.event||event is a dirty little trick:

在IE window.event 将评估事件对象并被用作从不评估表达式的结果(以便事件)。在非IE浏览器中, window.event 将评估为未定义(除非有人正在做一些非常糟糕的事情),因此结果将是事件变量。

In IE window.event will evaluate to the event object and be be used as the result of the expression (so that event) is never evaluated. In non-IE browsers, window.event will evaluate to undefined (unless someone is doing some really bad things) and thus the result will be that of the event variable.

将此转换为事件|| window.event 会导致浏览器(即IE)中的ReferenceError不支持W3C本地事件变量方法。

Reversing this to event||window.event would cause a ReferenceError in browsers (i.e. IE) that do not support the W3C local event variable approach.

这篇关于如何在内联添加事件侦听器时获取事件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆