For example, this calling method cannot be used: element.onclick = test(); element.onclick = test(arg1, arg2); only element.onclick = function(){ ... }; or element.onclick = test This is implemented in a different way, so parameters cannot be passed to the function. Referring to a large amount of online information, the way to solve this problem, taking the code as an example, is as follows:
function Handler() { };
Handler.prototype = {
/*
* Bind the eventType event to the element element and use the handler event handler Processing
* Compatible with browsers such as IE and Firefox
*
* @param element The object on which the event is registered (Object)
* @param eventType The registered event type (String), no Add "on"
* @param handler event handler (Function)
*/
registerEvent: function(element, eventType, handler) {
if(element.attachEvent) { //Level 2 DOM Event handling
element.attachEvent('on' eventType, handler);
}else if (element.addEventListener) {
element.addEventListener(eventType, handler, false);
} else { //Event processing of level 0 DOM
element['on' eventType] = handler;
}
},
/*
* Get a reference to the event handler with parameters
*
* @param obj The owner of the event processing function that needs to be bound, null represents the window object
* @param func The name of the event processing function that needs to be bound
* @param ... The third parameter The beginning is the parameters of the binding event handler function, consisting of 0 to more
*/
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) };
}
}
may be used as:
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")));//Using the 2-level event model
//$("txt").onchange = handler. bind(null,show,$("txt"));//JavaScript event attribute method
}