How to pass parameters to event handler? When I first came into contact with Javascript, I often struggled with this problem because I didn't have a deep understanding of closures.
I often encounter this problem in discussion groups, as follows
How to give event handler Pass parameters? Click me
How to pass the parameters v1 and v2 to the handler? The default event object will be passed in as the first parameter of the handler. When clicking the link, the first thing that pops up is the event object, and the second one is undefined.
Option 1, the unreserved event object is passed in as the first parameter
function handler(arg1,arg2){
alert(arg1);
alert(arg2);
}
E.on(document.getElementById('aa'),' click',function(){
handler(arg1,arg2);
});
Option 2, retain the event object as the first parameter
function handler(e,arg1,arg2){
alert(e);
alert(arg1);
alert(arg2);
}
E.on(document.getElementById('aa'),'click',function(e){
handler(e ,arg1,arg2);
});
Option three, add getCallback to Function.prototype and do not retain the event object
Function.prototype.getCallback = function(){
var _this = this, args = arguments;
return function (e) {
return _this.apply(this || window, args);
};
}
E.on(document.getElementById('aa'),'click',handler .getCallback(v1,v2));
Option 4, add getCallback to Function.prototype, retain the event object and pass it in as the first parameter
Function.prototype.getCallback = function(){
var _this = this, args = [];
for(var i=0,l=arguments.length;i args[i 1] = arguments[i];
}
return function(e) {
args[0] = e;
return _this.apply(this || window, args);
};
}
E.on(document.getElementById('aa'), 'click',handler.getCallback(v1,v2));