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 kind of problem in discussion groups, as follows:
Copy the code code as follows:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>How to pass parameters to event handler? </title>
</head>
<body>
<a href="#" id="aa">Click me</a>
<script type="text/javascript">
var E = {
on : function(el, type, fn){
el.addEventListener?
el.addEventListener(type, fn, false):
el.attachEvent("on" + type, fn);
},
un : function(el,type,fn){
el.removeEventListener?
el.removeEventListener(type, fn, false):
el.detachEvent("on" + type, fn);
}
};
var v1 = 'jack', v2 = 'lily';
function handler(arg1,arg2){
alert(arg1);
alert(arg2);
}
// How to pass parameters v1 and v2 to handler?
//The default event object will be passed in as the first parameter of the handler.
//At this time, the first thing that pops up when clicking the link is the event object, and the second one is undefined.
E.on(document.getElementById('aa'),'click',handler);
</script>
</body>
</html>
How to pass parameters v1 and v2 to 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 event object is not retained and passed in as the first parameter
Copy the code code 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 the code code 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 3: Add getCallback to Function.prototype without retaining the event object
Copy the code code 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 and retain the event object as the first parameter.
Copy the code code as follows:
Function.prototype.getCallback = function(){
var _this = this, args = [];
for(var i=0,l=arguments.length;i<l;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));