How to detach event in IE 6 7 8 9 using JavaScript

房东的猫 提交于 2019-12-04 07:28:31

base on this article, a cross-browser event handler can be :

var EventUtil = {
    addHandler: function(element, type, handler) {
        if (element.addEventListener) {
            element.addEventListener(type, handler, false);
        } else if (element.attachEvent) {
            element.attachEvent("on" + type, handler);
        } else {
            element["on" + type] = handler;
        }
    },
    removeHandler: function(element, type, handler) {
        if (element.removeEventListener) {
            element.removeEventListener(type, handler, false);
        } else if (element.detachEvent) {
            element.detachEvent("on" + type, handler);
        } else {
            element["on" + type] = null;
        }
    }
};

You need to pass to detachEvent the function you added with attachEvent. In your code you're passing a new one (they have the same toString() and would do the same thing but they're not the same).

You should make ff global with

var ff;
if (document.body.addEventListener) {
    document.body.addEventListener('mousemove', handler, false);
} else if (document.body.attachEvent) {
     ff=function(e) {
          return handler(e || window.event);
     };

and then call

else if (document.body.detachEvent) {
     document.body.detachEvent('onmousemove', ff);
} 

to remove the listener in old IE.

Note : I'm really doubtful about the document.body.removeAttribute("onclick"); : is there really a case in which this would be useful ?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!