zoukankan      html  css  js  c++  java
  • 事件的绑定以及兼容代码

    1. 事件的绑定:为同一个元素绑定多个相同的事件

    2. 三种方式

    (1)对象.on事件名字=事件处理函数

    my$("btn").onclick=function(){};

    如果是多个相同事件注册用这种方式,最后一个执行,之前的被覆盖了

    (2) 对象.addEventListener("没有on的事件名字",事件处理函数,false);

      --谷歌和火狐支持,IE8不支持

      my$("btn").addEventListener("click",function(){},false);

      参数1:事件的类型---事件的名字,没有on
      参数2:事件处理函数---函数(命名函数,匿名函数)
      参数3:布尔类型,目前就写false

    //为同一个元素绑定多个相同的事件
     my$("btn").addEventListener("click",function () {
       console.log("你好啊");
     },false);
     my$("btn").addEventListener("click",function () {
       console.log("你吃饭了吗");
     },false);

    (3)对象.attachEvent("有on的事件名字",事件处理函数);

      --谷歌不支持,火狐不支持,IE8支持

      参数1:事件类型---事件名字,有on
      参数2:事件处理函数---函数(命名函数,匿名函数)

      my$("btn").attachEvent("onclick",function(){});

     my$("btn").attachEvent("onclick",function () {
       console.log("小杨好帅哦1");
     });
    
     my$("btn").attachEvent("onclick",function () {
       console.log("小杨好帅哦2");
     });

    3.兼容代码

    //为任意元素.绑定任意的事件, 任意的元素,事件的类型,事件处理函数
      function addEventListener(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;
        }
      }
  • 相关阅读:
    进程与线程
    the art of seo(chapter seven)
    the art of seo(chapter six)
    the art of seo(chapter five)
    the art of seo(chapter four)
    the art of seo(chapter three)
    the art of seo(chapter two)
    the art of seo(chapter one)
    Sentinel Cluster流程分析
    Sentinel Core流程分析
  • 原文地址:https://www.cnblogs.com/zhangDY/p/11494886.html
Copyright © 2011-2022 走看看