HTML之事件处理程序

HTML事件

<body>
    <input type="button" value="按钮1" id="but1" onclick="click()">
    <script type="text/javascript">
    function click(){
        alert(this.value+"被点击了");
    }
</script>
</body>

DOM0级事件

<body>
    <input type="button" value="按钮1" id="but1">
    <script type="text/javascript">
    function click(){
        alert(this.value+"被点击了");
    }
    var but1 = document.getElementById("but1");
    but1.onclick = click;//添加
    but1.onclick = null;//移除
</script>
</body>

DOM2级事件

<body>
    <input type="button" value="按钮1" id="but1">
    <script type="text/javascript">
    function click(){
        alert(this.value+"被点击了");
    }
    var but1 = document.getElementById("but1");
    but1.addEventListener("click", click, false);//添加,参数false表示事件冒泡流,true表示捕获流
    but1.removeEventListener("click", click, false);//移除
</script>
</body>

IE8-版本事件

<body>
    <input type="button" value="按钮1" id="but1">
    <script type="text/javascript">
    function click(){
        alert(this.value+"被点击了");
    }
    var but1 = document.getElementById("but1");
    but1.attachEvent("onclick", click);//添加,没有参数false或true,是因为IE8以及更早的浏览器只支持事件冒泡流,
    but1.detachEvent("onclick", click);//移除
</script>
</body>

兼容写法

<body>
    <input type="button" value="按钮1" id="but1">
    <script type="text/javascript">
    function myClick(){
        alert(this.value+"被点击了");
    }
    var but1 = document.getElementById("but1");
   var eventUtil = {//封装事件处理程序
        addEvent:function(ele,type,fun){
            if(ele.addEventListener){
                ele.addEventListener(type, fun, false);
            }else if(ele.attachEvent){
                ele.attachEvent('on'+type, fun);
            }else{
                ele['on'+type] = fun;
            }
        },
        removeEvent:function(ele,type,fun){
            if(ele.removeEventListener){
                ele.addEventListener(type, fun, false);
            }else if(ele.detachEvent){
                ele.detachEvent('on'+type, fun);
            }else{
                ele['on'+type] = null;
            }
        }
    }
    eventUtil.addEvent(but1,'click',myClick);
</script>
</body>

 

posted @ 2015-05-13 22:15  caoruiy  阅读(266)  评论(0编辑  收藏  举报