javascript 擷取event

來源:互聯網
上載者:User

先從一個簡單的例子說起,一個簡單的button控制項如下:

<input type='button' name='mybtn' id='mybtn' onclick='myFunc()'/>

然後為其註冊事件,這樣的情況,怎麼在javascript裡擷取event呢,特別是firefox的情況。請看:

<script type='text/javascript'>
function myFunc(){
   var ev = window.event || arguments.callee.caller.arguments[0]
       ,et = ev.srcElement || ev.target;

   alert(et.tagName);   
}
</script>

不出意外的話,在ie/ff下,上面例子都將輸出INPUT,即是觸發click事件節點的標籤名,ie的event擷取這裡就不說了,重點說說ff下的情況。

這裡的arguments.callee.caller.arguments[0]看起來又長又怪,為什麼在firefox的情況下,這個東西就是event呢?

首先得瞭解arguments.callee是什麼東西,caller又是什麼樣的屬性?

argments.callee就是函數體本身,arguments.callee.caller就是函數體的調用函數體

簡單例子如下:

<script type='text/javascript'>
function a(){
    b();
}

function b(){
    alert(b === arguments.callee)
    alert(b.caller === a)
    alert(arguments.callee.caller === a)

}
a();
</script>

不出意外,上面的例子將輸出3個true,表明當a()調用時,函數b與函數a的關係。

好,弄清楚了arguments.callee與caller,我們再把原先的例子改改

Code
<script type='text/javascript'>
function myFunc(){
   alert(arguments.callee.caller.toString())
   var ev = window.event || arguments.callee.caller.arguments[0]
       ,et = ev.srcElement || ev.target;
}
</script>

我們把argument.callee.caller的函數體輸出,看看到底在ie和ff下有何區別.

可以看到ie下輸出為

function anonymous(){
  myFunc()
}

ff下輸出為

function onclick(event){
   myFunc();
}

由此看出在html控制項中直接註冊事件在ie/ff下表現的不同, ie下定義了一個匿名函數,內部再執行使用者定製的函數(myFunc),而ff下則有所

不同,首先ff下定義了一個與節時間點事件同名的函數,這裡是onclick事件,所以是function onclick,然後event作為一個參數傳入,內部再執行myFunc.

所以當事件觸發時,在myFunc裡,argument.callee.caller就是指向function onclick,當然,argument.callee.caller.arguments[0]即為event了.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.