原生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");

 

  

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM