JQuery: I can not set a value in a loop with a dynamic value

How come in the following code my update business function always updates the input with the final value in the array

for (var i = 0; i < results.length; i++) {
var place = results[i];
var input = $("<input/>").change(function(){update_business(place.name)});

...

}

function update_business(value){

$('#business input').val(value);
}

The problem here is that all those event handler functions are going to share exactly the same "place" variable; there's only one. Relative to the event handlers it's like a global variable.

You can write a separate function to help:

function makeHandler(place) {
     return function() {
       update_business(place.name);
     };
   }

Then you can call it in the loop:

var input = $('<input/>').change(makeHandler(place));

The function returns another function, which is the thing that'll actually be used as the event handler. Because the variable "place" from the loop is passed in as an argument to the "makeHandler" function, it's a unique copy of "place" at a particular iteration through the loop. Thus, each event handler has it's very own "place".

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章