JS技巧:JavaScript獲取事件對(duì)象的注意事項(xiàng)
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
平時(shí)我們獲取事件對(duì)象一般寫法如下: function getEvent(event) { return event || window.event // IE:window.event}如果沒有參數(shù),也可寫成(非IE :事件對(duì)象會(huì)自動(dòng)傳遞給對(duì)應(yīng)的事件處理函數(shù),且為第一個(gè)參數(shù)): function getEvent() { return arguments[0] || window.event // IE:window.event}這樣的寫法在除 Firefox(測(cè)試版本:3.0.12,下同) 外的瀏覽器上運(yùn)行都不會(huì)有問題,但 Firefox 為什么例外呢?讓我們這樣一種情形: <button id="btn" onclick="foo()">按鈕</button><script>function foo(){ var e = getEvent(); alert(e);}</script>運(yùn)行結(jié)果在 Firefox 中是 undefined,為什么呢? 在 Firefox 中調(diào)用其實(shí)是這樣的,先調(diào)用執(zhí)行的是: function foo(){ var e = getEvent(); alert(e);}然后調(diào)用執(zhí)行的是: function onclick( 因此,我們的 getEvent 可以優(yōu)化成(參照 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 || <button id="btn" onclick="foo(event)">按鈕</button> 該文章在 2010/8/17 23:17:54 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |