开发者

jQuery: I can't 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".


Your inner function has closure to the outer variable itself, not a copy of its value.

You need to pass it by value by not using the closed over variable, but a new one of whoms lifespan is briefer.

(function(j) {
    var place = results[j];
    ...
})(i);

Here the value of i is passed to the self invoking anonymous function as the j argument, and j will always be what i was at the time of that function being called.


.val() will replace the value instead of appending the value. try using .append if you wish to add on to your current value.

documentation here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜