开发者

Changing function parameters for onkeypress event according to source id

I want to assign a function according to their id to all the input fields in a web page. To do this I wrote below code but all the input fields are running keyPress with same parameter.. :(

///////////////////Checks all available 'text' 'input's////////////////////
var inputs = document.getElementsByTagName('input');
var cnvtrInput = new Array();
for (var index = 0; index < inputs.length; index++) {
 if (inputs[index].type == 'text') {
  cnvtrInput[index] = new converter(inputs[index]);
  inputs[index].onkeypress = function() {return keyPess(cnvtrInput[index])};
 }
}
//index--;

With the last commented statement I found that the passing element of keyPress is the last value of index;

Finally I tried same with textareas but failed...开发者_高级运维


You are creating functions in a loop which is always tricky. After the loop finished, index will have the value inputs.length and your callback is referencing index. But it won't work either if you define a new variable in a loop, as JavaScript has no block scope, only function scope.
You have to capture the value in a new scope, e.g. by using an immediate function:

inputs[index].onkeypress = (function(value) {
    return function() {return keyPess(value)};
}(cnvtrInput[index]));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜