samedi 27 juin 2015

How to maintain proper variable scope/value in function call nested in loop [duplicate]

This question already has an answer here:

I ran into a scope problem when dealing with generated HTML plus event handling from within a loop.

Imagine this scenario

# var container=$('#someContainerId');

_buildField=function(index){
    return $('<div/>').data('index', index);
};

for(var i=1; i<=10; i++){
    container.append( $('<div/>').on('click', function(){
        _buildField(i);
    } );
}

In this example, _buildField() will always receive the value 10, no matter which of the div elements is being clicked.

Quite honestly, i thought it to be different, but here we go again, learning something new.

QUESTION

How can i assure the passing of the correct value (current iteration stored in i) to _buildField()?

Aucun commentaire:

Enregistrer un commentaire