• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

奋斗中...

曾经的程序员。ASP.NET/C#, JavaScript, PL/SQL, T-SQL; 工具: VS2003/2005, Oracle, SQLServer; 偶尔写点CSS, 批处理.
头脑中经常有新想法, 可惜没有去实现.
Never give up.
Never get into a fight with a pig. Both of you will get dirty. But the pig actually enjoys it.
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

[JavaScript]注册事件的方法

考虑跨浏览器

addEventListener和attachEvent的第一参数中,事件名是否带"on".

参考文档:

http://phrogz.net/JS/AttachEvent_js.txt

防止链接失效,转帖如下:

//*** This code is copyright 2003 by Gavin Kistner, !@phrogz.net
//
*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
//
*** Reuse or modification is free provided you abide by the terms of that license.
//
*** (Including the first two lines above in your source code satisfies the conditions.)


//***Cross browser attach event function. For 'evt' pass a string value with the leading "on" omitted
//
***e.g. AttachEvent(window,'load',MyFunctionNameWithoutParenthesis,false);

function AttachEvent(obj,evt,fnc,useCapture){
if (!useCapture) useCapture=false;
if (obj.addEventListener){
obj.addEventListener(evt,fnc,useCapture);
return true;
}
else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
else{
MyAttachEvent(obj,evt,fnc);
obj[
'on'+evt]=function(){ MyFireEvent(obj,evt) };
}
}

//The following are for browsers like NS4 or IE5Mac which don't support either
//
attachEvent or addEventListener
function MyAttachEvent(obj,evt,fnc){
if (!obj.myEvents) obj.myEvents={};
if (!obj.myEvents[evt]) obj.myEvents[evt]=[];
var evts = obj.myEvents[evt];
evts[evts.length]
=fnc;
}
function MyFireEvent(obj,evt){
if (!obj || !obj.myEvents || !obj.myEvents[evt]) return;
var evts = obj.myEvents[evt];
for (var i=0,len=evts.length;i<len;i++) evts[i]();
}

posted on 2011-02-18 14:22  jes  阅读(296)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3