跨浏览器的事件处理程序

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>handler</title>
</head>
<body>
<button id="btn">click</button>
<script>
    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;
            }
        }
    };
    var handler = function() {
        console.log('handler');
    };
    var oBtn = document.getElementById('btn');
    EventUtil.addHandler(oBtn, 'click', handler);
    EventUtil.removeHandler(oBtn, 'click', handler);
</script>
</body>
</html>

 

posted @ 2018-02-07 23:32  井凉一一  阅读(132)  评论(0编辑  收藏  举报