16.事件绑定

HTML:




Insert title here



    
    
    
    
    
    
    
    
    


JS:
//方式1:不能重复绑定
function click1(event,srcEl){
    //alert("被点了");
    console.log(event);
    console.log(srcEl);
}


//方式2:不能重复绑定
/*window.onload = function(){
    //获取到数据源
    var btn2 = document.getElementById("btn2");
    
    //绑定点击事件
    btn2.onclick = function(event){
        //event为非IE浏览器和IE11以上才能使用的方式
        //window.event为IE11以下使用的方式
        console.log(event||window.event);
        console.log(this);
    };
};*/

//方式 3:使用方法来完成对元素的监听,可以实现多事件绑定
window.onload = function(){
    var btn = document.getElementById("btn3");
    
    //IE添加的方式.一定要有on才可以
    /*btn.attachEvent("onclick", function(event){
        console.log(event);
        console.log("方式3-->IE");
    });*/
    
    //非IE添加的方式.
    /*btn.addEventListener("click", function(event){
        console.log(event);
        console.log("方式3-->非IE");
    });*/
    
    //适配方法
    addEvent(btn,"click",function(){
        console.log("方式3-->非IE");
    });
    
};
//适配IE和非IE 参数1:事件源   参数2:事件类型(IE事件加on,非IE事件不加)
function addEvent(srcEl,eventType,fn){
    if(srcEl.attachEvent){//如果个属性有值,使用IE方式
        srcEl.attachEvent("on"+eventType,fn);
    }else{//如果没有值,使用非IE方式
        srcEl.addEventListener(eventType,fn);
    }
}


你可能感兴趣的:(16.事件绑定)