0

I believe everyone use javascript would run into this problem but because I don't really know how closure works I can't solve it myself.

    var hint = ["str", "str", "str", "str", "str"];
    var inputIDs = ["ip-name", "ip-pwd", "ip-pwd-cfm", "ip-email", "ip-phone"];
    var errorMsg = [];
    for (var i = 0; i<hint.length; i++) {
        document.getElementById(inputIDs[i]).addEventListener("focus", function (e) {
            var tar = e.target.parentElement.getElementsByClassName("alert")[0];
            tar.innerHTML = hint[i];
        });
    }

I want to bind focus event to every element iteratively. But if I use the code above, every time the function is executed, i is 5.

I think I should use closure here to get the value of i correct as I wanted.

Can anyone give a suggestion?

jinglei
  • 3,269
  • 11
  • 27
  • 46

2 Answers2

0

Create a closure inside the loop and bind it with i

var hint = ["str", "str", "str", "str", "str"];
var inputIDs = ["ip-name", "ip-pwd", "ip-pwd-cfm", "ip-email", "ip-phone"];
var errorMsg = [];
for (var i = 0; i < hint.length; i++) {
  (function(i) { // creating a closure
    document.getElementById(inputIDs[i]).addEventListener("focus", function(e) {
      var tar = e.target.parentElement.getElementsByClassName("alert")[0];
      tar.innerHTML = hint[i];
    });
  }(i))

}
brk
  • 48,835
  • 10
  • 56
  • 78
0

The simpler and cleaner solution in my opinion is to use forEach, below a working example, you can focus in input tags to see the result in console.

var hint = ["str", "str", "str", "str", "str"];
var inputIDs = ["ip-name", "ip-pwd", "ip-pwd-cfm", "ip-email", "ip-phone"];
var errorMsg = [];
inputIDs.forEach(function(item, i){
  document.getElementById(inputIDs[i]).addEventListener("focus", function(e) {
  console.log(i);
  // I comment out this code just to keep this example more simple  
  //var tar = e.target.parentElement.getElementsByClassName("alert")[0];
  //tar.innerHTML = hint[i];
  });
});
<input id="ip-name" type="text">
<input id="ip-pwd" type="text">
<input id="ip-pwd-cfm" type="text">
<input id="ip-email" type="text">
<input id="ip-phone" type="text">
GibboK
  • 71,848
  • 143
  • 435
  • 658