js中的事件关键字 [英] Event keyword in js

查看:129
本文介绍了js中的事件关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个代码令人担忧,在chrome,ff和ie中。但是,我无法在网络中找到任何魔术事件关键字的引用。请参阅

 < HTML> 
< head>
< script type =text / javascript>
函数处理程序(e)
{
alert(e);
}
< / script>
< / head>
< body>

< h1 onclick =handler(event); alert(0)>单击此文本< / h1>

< / body>
< / html>

如果我更改事件,这个脚本STOPS工作在括号内的别的东西。这是不推荐的关键字吗?

解决方案

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

如果您想了解有关事件处理的更多信息,建议您在 quirksmode.org



还可以看看 MDC - 事件处理程序


对应于HTML'on'事件属性。



与相应的属性不同,这些属性的值是函数(或实现EventListener接口的任何其他对象),而不是一个字符串事实上,在HTML中分配一个事件属性会围绕指定的代码创建一个包装函数。例如,给定以下HTML:

 < div onclick =foo();>点击我! / DIV> 

如果元素是对这个 div element.onclick 的值有效地:

  function onclick(event){
foo();
}

注意事件对象如何作为参数事件传递到这个包装函数。



I found this code worling in chrome, ff and ie. However, I can't find any references to the "magic" event keyword in the web. See 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>

This scripts STOPS working if I change event in brackets to something else. Is that a deprecated keyword?

解决方案

The Event object is automatically passed to all event handlers. If you add event handlers with addEventListener, you can choose the parameter name (like you did in handler). But for code attached with the onclick attribute, you can only access the event object via the implicit variable event.

If you want to know more about event handling in general, I suggest to read about it at quirksmode.org.

Also have a look at 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.

这篇关于js中的事件关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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