DIV CSS 佈局教程網

JavaScript 取得事件物件時不可忽略的細節
編輯:關於JavaScript     

平常我們取得事件物件的一般寫法如下:

function getEvent(event) {
    return event || window.event  // IE:window.event
}

如果不帶參數,也可以寫成(非 IE 瀏覽器會把事件物件自動傳給對應的事件處理函式,且作為第一個參數):

function getEvent() {
    return arguments[0] || window.event // IE:window.event
}

這樣的寫法在除 Firefox(測試版本:3.0.12,下同)以外的瀏覽器上都不會有問題,但 Firefox 為什麼是例外呢?看看這樣一種情形:

<button id="btn" onclick="foo()">按鈕</button>

<script>
function foo(){
   var e =  getEvent();
   alert(e);
}
</script>

執行結果在 Firefox 中是 undefined,為什麼呢?

在 Firefox 中,實際呼叫的過程是先執行:

function foo(){
   var e =  getEvent();
   alert(e);
}

然後才執行:

function onclick(event) {
    foo();
}

可以發現,在 Firefox 下 onclick="foo()" 中的 foo() 無法自動傳入事件物件參數,事件物件預設被傳給了系統產生的 onclick 函式。就本例而言,我們可以透過 getEvent.caller.caller.arguments[0] 取得事件物件。

因此,getEvent 可以優化為(參照 yui_2.7.0b 中 event/event-debug.js 的 getEvent 方法):

function getEvent(event) {
        var ev = event || window.event;

        if (!ev) {
                var c = this.getEvent.caller;
                while (c) {
                        ev = c.arguments[0];
                  if (ev && (Event == ev.constructor || MouseEvent  == ev.constructor)) { //怿飛注:YUI 源碼 BUG,ev.constructor 也可能是 MouseEvent,不一定是 Event
                  break;
                  }
                c = c.caller;
                }
        }

        return ev;
}

當然,還有一個很簡單的解法,就是手動把參數傳給 onclick="foo()":

<button id="btn" onclick="foo(event)">按鈕</button>

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved