事件是一个全局变量,可以在回调链中的任何地方访问? [英] is event a global variable that is accessible everywhere inside the callback chain?

查看:125
本文介绍了事件是一个全局变量,可以在回调链中的任何地方访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩DOM和javascript的事件监听器,并注意到:

I was just playing around with event listeners with DOM and javascript and did notice this:

function chained(msg) {
    console.log(msg, event);
}

function onClick() {
    chained('the body was clicked');
}

document.body.addEventListener('click', onClick);

现在有趣的事情...这将输出:

Now the funny thing...this will output:


身体被点击,(MouseEvent)

"the body was clicked, (MouseEvent)"

然后我问,为什么?如何在链接通话之前传递事件对象?

Then I ask, why? how does it passes the event object without sending it on the chained call?

function chained(msg) {
    console.log(msg, namedEventObj); //throw error namedEventObj is not defined
}

function onClick(namedEventObj) {
    console.log(event); //outputs (MouseEvent);
    console.log(nameEventObj); //outputs (MouseEvent);
    chained('the body was clicked');
}

document.body.addEventListener('click', onClick);

即使我声明事件obj在 onClick 函数作为 namedEventObj 它将仅可用于 onClick 而不是链接函数...我得到这个,这对我来说很有意义,但绝对不是事件变量可用于链接功能。

Even If I declare the event obj to be passed on the onClick function as namedEventObj it will available only to onClick but not to chained function...I got this and this makes sense for me...but definitely not the event variable to be available to the chained function.

任何人都知道为什么它的行为是这样的?

Anyone know why does it behaves like this?

我可以想到的唯一的事情是,事件实际上是 window.event ,并且在某些事件调度和事件...时它可以使用,但这意味着任何元素可以在触发事件的同时调用事件信息?

The only thing I can think of is that event is in fact window.event and it makes itself available when some event dispatches and Event...but that would mean that any element could get that event information if called at the same time as the event when it triggers?

我正在使用Chrome 11.0.x

I am using Chrome 11.0.x

推荐答案

可以通过 window.event 访问当前事件。只需使用事件隐式访问 window.event

One can access the current event through window.event. Just using event is implicitly accessing window.event.

这篇关于事件是一个全局变量,可以在回调链中的任何地方访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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