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()
?