事件处理程序的几种方式

第一种:

<button type="button" id="myBtn" value="确定" onclick="showMessage()"></button>

function showMessage(){

   alert("hello world"); 

}

第二种:

var obj=document.getElementById("myBtn");

obj.onclick=function(){

 alert("hello world"); 

}

第三种:

obj.addEventlistener("click",function(){

alert("hello world"); 

})

ps:当触发事件处理程序时,会产生一个event对象,这个event对象包含着所有与事件相关的信息。包括事件的元素、事件类型以及其相关信息。比如鼠标操作中包含鼠标位置信息;键盘操作中包含按下键的信息。

var obj=document.getElementById("myBtn");

obj.onclick=function(event){

 alert(event.currentTarget); 

}

obj.addEventlistener("click",function(event){

alert(event.type); 

})

原文地址:https://www.cnblogs.com/suhaihong/p/6490589.html