JavaScript绑定事件跟解绑事件的兼容代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<input type="button" value="按钮" id="bt"/>
<input type="button" value="解绑事件" id="bt2"/>
<script src="common.js"></script>
<script>
    //绑定事件兼容代码
    function addEventListner(element, type, fn) {
        if (element.addEventListener) {
            element.addEventListener(type, fn, false);
        } else if (element.attachEvent) {
            element.attachEvent("on" + type, fn);
        } else {
            element["on" + type] = fn;
        }
    }
    //解绑事件的兼容代码
    function removeEventListner(element, type, fnName) {
        if (element.removeEventListener) {
            element.removeEventListener(type, fnName, false);
        } else if (element.detachEvent) {
            element.detachEvent("on" + type, fnName);
        } else {
            element["on" + type] = null;
        }
    }

    //测试
    function f1() {
        console.log("第一个");
    }
    function f2() {
        console.log("第二个");
    }
    addEventListner(my$("bt"), "click", f1);
    addEventListner(my$("bt"), "click", f2);
    my$("bt2").onclick = function () {
        removeEventListner(my$("bt"), "click", f1);
    };
</script>
</body>
</html>

 

posted @ 2018-07-29 20:44  {颜逸}  阅读(438)  评论(0编辑  收藏  举报