事件处理程序的第一个参数 [英] First parameter to event handler

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

问题描述

如果我有一些与我的标记内联注册的事件处理程序(不推荐,我知道),如

If I have some event handlers registered inline with my markup (deprecated, I know) like

 span id="..." onclick="foo(p1,p2,p3)"

我该如何访问事件事件处理函数foo中的对象?将上述更改为

how can I access the "event" object in the event handler function foo? Changing the above to

 span id="..." onclick="foo(event,p1,p2,p3)"

然后在foo中使用它

function foo(e,p1,p2,p3)
{
   if (!e) e = window.event;
}

似乎有效,但我没有看到任何记录,所以我很谨慎使用它。换句话说,内联事件处理程序的第一个参数始终是事件对象,如果它被命名为在onclick = ...标记?这个跨浏览器是否可以安全使用?如果它没有这样命名(如我的第一个例子),参数被视为常规参数而事件对象未被传递?

seems to work but I don't see it documented anywhere so I am wary of using it. In other words, is the first parameter to a inline event handler always the event object if it is named as such in the onclick=... markup? Is this cross-browser so it can be safely used? And if it is not named as such (as in my first example), the parameters are treated like regular parameters and the event object is not passed?

思考?谢谢

推荐答案

你误解了你的代码。

字符串你放入内联处理程序是一个正常的Javascript代码。它不需要是单个函数调用;它甚至可以包含多个语句(像往常一样用分号分隔)

The string that you put in the inline handler is a normal piece of Javascript code. It does not need to be a single function call; it can even contain multiple statements (separated by semicolons, as usual)

内联处理程序中的代码将被赋予一个名为 event的变量引用事件对象。

The code in the inline handler will be given a variable called event which refers to the event object.

当你写 onclick =foo(event,p1,p2,p3)时,你正在进行常规函数调用,并传递名为 event p1 p2 ,以及 p3 作为函数的参数。

When you write onclick="foo(event,p1,p2,p3)", you're making a regular function call, and passing the values of four variables named event, p1, p2, and p3 as parameters to the function.

这篇关于事件处理程序的第一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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