js事件定义方式和获取事件对象event总结

js中事件的定义方式有3种:标签内事件属性,dom元素事件属性 和 dom元素添加事件的方法。

1.标签内事件属性://事件处理函数内this 指向事件源元素

<div id="adiv" onclick="alert(event.type);">a div</div>

标签内事件属性其实是一个匿名函数,在ie中等价于 $('adiv').onclick=function(){alert(event.type);}  在FF中 等价于 $('adiv').onclick=function(event){.....}

因为 在ie中 event对象是在事件发生时创建的,作为window对象的属性存在,全局范围内可访问;在FF中 event对象是作为事件处理函数的第一个参数传入的,函数体内可用 event或arguments[0]引用

2.dom元素事件属性: //事件处理函数内this 指向事件源元素

$("adiv").onclick=function(){alert(event.type);}; //ie only. 在ie中 event对象是在事件发生时创建的,作为window对象的属性存在,全局范围内可访问

$("adiv")['onclick']=function(){alert(event.type);};

$('adiv').onclick=function(e){alert(e.type);}; //ff, 事件处理函数的第一个参数就是event对象,参数名称可自定义 如 e,  ev event....

$('adiv')['onclick']=function(e){alert(e.type);};

3.dom元素的事件相关方法 //事件处理函数内this不指向 事件源元素,需要用 event.srcElement 或 event.target引用

$('adiv').attachEvent('onclick',function(){alert(event.type);});  // ie only

$('adiv').addEventListener('click',function(e){alert(e.type);},false); // FF

原文地址:https://www.cnblogs.com/stephenykk/p/3092745.html