原生js事件绑定和事件移除

分类:Javascript| 发布:camnprbubuol| 查看: | 发表时间:2013/7/3

用惯了框架,什么jQuery/Ext/zepto/underscore/backbone 绑定事件on,bind,addListener,如果没有这些框架,原生的js怎么写?你能立刻写出来吗? 绑定事件的好处:

  • 一个对象可以绑定多个不同事件
  • 一个对象可以绑定多个相同事件(按照绑定的顺序执行。注意IE下顺序相反)

测试地址

js代码如下:

/**
 * @description 事件绑定,兼容各浏览器
 * @param target 事件触发对象 
 * @param type   事件
 * @param func   事件处理函数
 */
function addEvents(target, type, func) {
    if (target.addEventListener)    //非ie 和ie9
        target.addEventListener(type, func, false);
    else if (target.attachEvent)   //ie6到ie8
        target.attachEvent("on" + type, func);
    else target["on" + type] = func;   //ie5
};

/**
 * @description 事件移除,兼容各浏览器
 * @param target 事件触发对象
 * @param type   事件
 * @param func   事件处理函数
 */
function removeEvents(target, type, func){
    if (target.removeEventListener)
        target.removeEventListener(type, func, false);
    else if (target.detachEvent)
        target.detachEvent("on" + type, func);
    else target["on" + type] = null;
};
365据说看到好文章不转的人,服务器容易宕机
原创文章如转载,请注明:转载自郑州网建-前端开发 http://camnpr.com/
本文链接:http://camnpr.com/javascript/native-js-event-bindings-and-removed.html