How do I pass arguments to an event handler? When it comes to JavaScript, the problem is often tangled up by the lack of understanding of closures.
Such problems are often encountered in the discussion group, as follows
Copy Code code as follows:
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title> How do I pass parameters to an event handler? </title>
<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 the parameter v1,v2 to handler?
The default event object is passed as the first argument to the handler,
Then click on the link the first pop-up is the event object, the second is undefined.
E.ON (document.getElementById (' AA '), ' click ', handler);
</script>
</body>
How to pass the parameter v1,v2 to handler? The default event object will be passed in as the first argument to the handler, when clicking the link the first pop-up is the event object, and the second is undefined.
Scenario one, the event object is not preserved as the first argument passed in
Copy Code code as follows:
function Handler (ARG1,ARG2) {
alert (ARG1);
alert (ARG2);
}
E.ON (document.getElementById (' AA '), ' click ', function () {
Handler (ARG1,ARG2);
});
Scenario two, keep the event object as the first argument
Copy 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);
});
Scenario three, add Getcallback to Function.prototype, do not preserve event objects
Copy 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));
Scenario four, add a getcallback to Function.prototype, and keep the event object passed in as the first argument
Copy 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));