jQuery events and event objects
First, let’s take a look at the ways we often use to add events:
javascript中的事件 单击事件 1单击事件 2
We most often add events by adding onclick element attributes to elements.
Add onclick events for testDiv2 The method is to modify the Dom attribute.
In the previous chapter, we have explained what element attributes and Dom attributes are. The effect of these two methods is the same. When you click the div, a prompt box will be displayed.
Please note that although the effect is the same, it is not equivalent.
document.getElementById("testDiv2").onclick = showMsg;
Equivalent to:
单击事件 1
Have you noticed the difference between the two? We often modify element attributes by adding The event method actually creates an anonymous function:
document.getElementById("testDiv1").onclick = function(event) { alert("!!!"); };
The signature of this anonymous function is the same as our handwritten showMsg signature, so showMsg can be directly assigned to onclick.
This kind of The disadvantages of this method are:
1. Only one event handling function can be bound to an event. Using "=" assignment will flush out all event handling functions previously bound to this time.
2. The method of obtaining the event object in the event function (whether it is an anonymous function or a bound function) requires special processing in different browsers:
In IE, the event object is a property of the window object. .The event handling function must access the event object like this:
obj.onclick=function() { var oEvent = window.event; }
In the DOM standard, the event object must be passed to the event processing function as the only parameter:
obj.onclick=function() { var oEvent = arguments[0]; }
In addition to using argument[0] to access this parameter , we can also specify the parameter name. The above code is equivalent to:
obj.onclick=function(oEvent) { }
Currently DOM-compatible browsers include Firefox, Safari, Opera, IE7, etc.
3. Add multicast delegation The functions are different in different browsers.
The following is the compatible multi-browser adding multicast provided in the article "Javascript Public Script Library Series (2): Methods to Add Event Multicast Delegate" Delegate method:
//统一的为对象添加多播事件委托的方法 /* 参数说明: oTarget : 要添加事件的对象.比如"document". sEventType : 事件类型.比如单击事件"click". fnHandler : 发生事件时调用的方法. 比如一个静态函数"hideCalendar"
Usage example:
//单击页面的任何元素,只要没有取消冒泡,都可以关闭日历控件 var cf = document.getElementById("CalFrame"); if( cf != null && hideCalendar != null ) { ScriptHelper.addEventListener( document, "click", hideCalendar ); } */ scriptHelper.prototype.addEventListener = function(oTarget, sEventType, fnHandler) { if( oTarget.addEventListener )//for dom { oTarget.addEventListener( sEventType, fnHandler, false ) } else if( oTarget.attachEvent )//for ie { oTarget.attachEvent( "on" + sEventType, fnHandler); } }
So we should first abandon the modification of