DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
IE 和 Firefox 下編寫 JavaScript 的差異(六):用 caller 與 arguments 找回 event
編輯:CSS詳解     

Firefox 沒有 window.event,這讓很多非直接掛在事件上的函數拿不到事件對象。好消息是,靠著兩個鮮為人知的函數屬性,我們可以把 event 找回來。

func.caller

JavaScript 中函數有一個 caller 屬性,指向呼叫它的函數:

function A() { B(); }
function B() { alert(B.caller); }

若 B 是被 A 呼叫的,那麼 B.caller 就是 A。

arguments

函數還有一個 arguments 屬性,可以遍歷當前傳入的參數:

function myalert() {
  var arr = [];
  for (var i = 0; i < myalert.arguments.length; i++) {
    arr[i] = myalert.arguments[i];
  }
  alert(arr.join("-"));
}
myalert("hello", "world", 1, 2, 3);

這會顯示 hello-world-1-2-3。要注意 arguments 的個數取決於呼叫方傳入的實參數量,與函數本身的參數定義無關。

結合兩者取得 event 對象

關鍵洞察在於:Firefox 在呼叫事件處理函數時,會把 event 當成第一個實參傳入,即使函數沒有宣告任何參數。因此沿著呼叫鏈往上找,就能撈到那個 event。

btn.onclick = handle_click;

function handle_click() {
  showcontent();
}

function showcontent() {
  var evt = SearchEvent();
  if (evt && evt.shiftKey) { // 若為事件呼叫且按下了 shift
    window.open(global_helpurl);
  } else {
    location.href = global_helpurl;
  }
}

function SearchEvent() {
  func = SearchEvent.caller;
  while (func != null) {
    var arg0 = func.arguments[0];
    if (arg0) {
      if (arg0.constructor == Event) return arg0;
    }
    func = func.caller;
  }
  return null;
}

這個例子的運作過程是:SearchEvent.caller 是 showcontent,但 showcontent.arguments[0] 是空的,所以 func = func.caller 之後 func 變成 handle_click。handle_click 是由 Firefox 直接呼叫的事件處理器,雖然沒定義參數,被呼叫時第一個實參就是 event,因此 handle_click.arguments[0] 正是我們要找的 event。這裡的 'Event' 是 Firefox 中 event 的 constructor 名稱。

下一步

有了這套邏輯,就能搭配 prototype.__defineGetter__ 在 Firefox 下模擬出 window.event,讓舊程式碼不必大改即可跨瀏覽器運作。

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