I have the following code in my ajax query:
xhr.onreadystatechange = stateChange;
and the function stateChange is function stateChange(event)
Is it possible to add a second parameter to the function so it doesn't just passes a number as well as the event?
I've tried doing xhr.onreadystatechange = stateChange(event,'123');
with function stateChange(event,num)
but it doesn't seem t开发者_JAVA技巧o work.
You can create a closure that allows your event handling function access to those variables.
Instead of
xhr.blahblah;
xhr.onreadystatechange = stateChange;
xhr.blahblah;
This technique creates an anonymous function that gives scope to your '123' variable:
xhr.blahblah;
function (xhrObj, callbackFn, param) {
xhrObj.onreadystatechange = function (event) {
callbackFn(event, param);
};
}(xhr, stateChange, '123');
xhr.blahblah;
Mmmm, sort of:
xhr.onreadystatechange = function(event) { stateChange(event,'123'); };
would do what you say you want, but it isn't clear to me that what you say you want is what you need.
精彩评论