原生Js事件绑定的三种方式

  • html标签事件绑定:属性赋值 ,这个在该元素的properties属性中可以查到, 也可以在事件监听中看到
function show(){
  console.log('show');
}

function print(){
  console.log('print');
}

<button onclick="show()" id="btn1" onclick="print()">html标签事件绑定</button>
//触发的方法只有show方法

<button onclick="show();print()" id="btn1">html标签事件绑定</button>
//一个事件,触发两个方法
  • js事件绑定:属性赋值,这个在该元素的properties属性中可以查到,也可以在事件监听中看到
<button id="btn2">js事件绑定</button>

 document.getElementById("btn2").onclick = show;
 document.getElementById("btn2").onclick = print;

//只能触发print方法,如果需要同时触发两个方法,只能使用事件监听
  • 事件监听:只可以在该元素的事件监听中看到
<button id="btn3">事件监听</button>      

//show和print两个方法都可以触发
document.getElementById("btn3").addEventListener("click",show);
document.getElementById("btn3").addEventListener("click",print);

//移除事件监听
document.getElementById("btn3").removeEventListener("click");

 

  

  

posted @ 2019-07-11 10:46  五两饭  阅读(53929)  评论(0编辑  收藏  举报