In JavaScript, in order to achieve separation of performance and control, we can achieve this through level 0 DOM Event attributes or Level 2 event model, however, when calling the corresponding event handle for an event type, the two cannot provide parameters for the event handle, that is, the event attribute value can only be a function reference. For example, this call method cannot be used: element. onclick = test (); element. onclick = test (arg1, arg2); only element. onclick = function (){...}; or element. onclick = test. Therefore, parameters cannot be passed to the function. Based on a large amount of online materials, the solution to this problem is as follows:
The Code is as follows:
Function Handler (){};
Handler. prototype = {
/*
* Bind events of the eventType type to the element and use the handler event handle for processing.
* Compatible with IE, Firefox, and other browsers
*
* @ Param element registers the event Object on it (Object)
* @ Param eventType: The Event Type (String) registered without "on"
* @ Param handler event handle (Function)
*/
RegisterEvent: function (element, eventType, handler ){
If (element. attachEvent) {// Level 2 DOM Event Processing
Element. attachEvent ('on' + eventType, handler );
} Else if (element. addEventListener ){
Element. addEventListener (eventType, handler, false );
} Else {// level 0 DOM Event Processing
Element ['on' + eventType] = handler;
}
},
/*
* Get the reference of the event handle with Parameters
*
* @ Param obj: the owner of the event handler function to be bound. null indicates the window object.
* @ Param func name of the event handler function to be bound
* @ Param... the third parameter starts to be the parameter bound to the event processing function, which consists of 0 to multiple
*/
Bind: function (obj, handler ){
Obj = obj | window;
Var args = [];
For (var I = 2; I <arguments. length; I ++)
{
Args. push (arguments [I]);
}
Return function () {handler. apply (obj, args )};
}
}
It may be used in the following ways:
Function show (txtObj ){
Alert (txtObj. value );
TxtObj. focus ();
TxtObj. select ();
}
Window. onload = function (){
Var handler = new Handler ();
Handler. registerEvent ($ ("txt"), "change", handler. bind (null, show, $ ("txt"); // uses a level-2 event model.
// $ ("Txt"). onchange = handler. bind (null, show, $ ("txt"); // method of JavaScript event attributes
}