javascript - How to bind events to an array of elements in a loop using closure? -


this question has answer here:

i believe use javascript run problem because don't know how closure works can't solve myself.

    var hint = ["str", "str", "str", "str", "str"];     var inputids = ["ip-name", "ip-pwd", "ip-pwd-cfm", "ip-email", "ip-phone"];     var errormsg = [];     (var = 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 bind focus event every element iteratively. if use code above, every time function executed, i 5.

i think should use closure here value of i correct wanted.

can give suggestion?

create closure inside loop , bind i

var hint = ["str", "str", "str", "str", "str"]; var inputids = ["ip-name", "ip-pwd", "ip-pwd-cfm", "ip-email", "ip-phone"]; var errormsg = []; (var = 0; < hint.length; i++) {   (function(i) { // creating closure     document.getelementbyid(inputids[i]).addeventlistener("focus", function(e) {       var tar = e.target.parentelement.getelementsbyclassname("alert")[0];       tar.innerhtml = hint[i];     });   }(i))  } 

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -