Home  >  Article  >  Web Front-end  >  Summary of four ways to pass parameters to event response functions_javascript skills

Summary of four ways to pass parameters to event response functions_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:10:381092browse

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

Copy code The code is 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


Copy the code The code is as follows:
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

Copy code The code is as follows:
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

Copy the code The code is as follows:
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

Copy code The code is as follows:
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));

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn