我发现此代码适用于 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 thisdiv
, the value ofelement.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/