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

时间:2021-12-01 04:35:32
<!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>