問題描述
我只是在玩弄 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)"
那我問,為什么?它如何傳遞事件對象而不在 chained
調用中發送它?
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);
即使我將要在 onClick
函數上傳遞的事件 obj 聲明為 namedEventObj
它也只能用于 onClick
而不能用于 chained
函數...我知道了,這對我來說很有意義...但絕對不是 event
變量可用于 chained
函數.
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
訪問當前事件.僅僅使用 event
就是隱式訪問 window.event
.
One can access the current event through window.event
. Just using event
is implicitly accessing window.event
.
這篇關于事件是回調鏈中隨處可訪問的全局變量嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!