javascript - js中的事件关键字

标签 javascript events

我发现此代码适用于 Chrome、FF 和 IE。但是,我在网络上找不到任何对“magic”event 关键字的引用。参见 this

<html>
    <head>
        <script type="text/javascript">
            function handler(e){
                alert(e);
            }
        </script>
    </head>
    <body>
        <h1 onclick="handler(event);alert(0)">Click on this text</h1>
    </body>
</html>

如果我将括号中的 event 更改为其他内容,此脚本将停止工作。这是已弃用的关键字吗?

最佳答案

Event object自动传递给所有事件处理程序。如果您使用 addEventListener 添加事件处理程序,您可以选择参数名称(就像您在 handler 中所做的那样)。但是对于带有onclick属性的代码,只能通过隐式变量event访问事件对象。

如果您想了解更多关于一般事件处理的信息,我建议您阅读 quirksmode.org。 .

另请查看 MDC - Event handlers :

These are properties that correspond to the HTML 'on' event attributes.

Unlike the corresponding attributes, the values of these properties are functions (or any other object implementing the EventListener interface) rather than a string. In fact, assigning an event attribute in HTML creates a wrapper function around the specified code. For example, given the following HTML:

<div onclick="foo();">click me!</div>

If element is a reference to this div, the value of element.onclick is effectively:

function onclick(event) {
   foo();
}

Note how the event object is passed as parameter event to this wrapper function.

关于javascript - js中的事件关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4968194/

相关文章:

javascript - 如何在 Odoo 10 中应用 jquery/javascript 照片标签代码

javascript - 将 php 数组传递给 javascript 变量,然后传递给服务器

javascript - 意外 token 模块构建失败 : SyntaxError

c# - 所有文本框的一个事件

java - 安卓图像按钮

python - 使用 PyQt4 在 QWidget 上使用 eventFilter

c# - 为什么要在方法足够的地方使用事件?

javascript - 在 jQuery 中通过 alt 属性定位 <img>

javascript - 如何获取所选值以显示下拉菜单

jquery - "Shift + Arrow key"的键码是什么?