I've been struggling with this one for several hours, a hint from someone who's had a similar coding situation would be welcome.
Using jQuery, I'm trying to bind a click event to dynamically generated spans. I have a fair understanding of variable scope in JavaScript but I'm obviously missing something as to how scopes work in conjunction with binding of events. Looking at other threads about scope issues did not help (not my usage scenario).
I've boiled it down to a minimal test. The jsfiddle is here: http://jsfiddle.net/xkT25/ Make sure you run it with the console open.
The interesting part is:
/** Add the click event handler to each span**/
for ( var i = 0; i < phones.length ; i++ ) {
var span = $( '<span class="phone">' + phones[i].phone + '</span>' );
console.log( 'phoneposition before .on(): ', phoneposition, span );
span.on( 'click', function() {
// WHY IS phoneposition ALWAYS 4? (expecting an index between [0-3]
console.log( ' phoneposition:' , phoneposition );
});
phoneposition++
html = html.add( span );
}
which results in a value of 4 all of the time. Instead, I need clicking letters to produce 0 for A, 1 for B, etc in the console.
PLEASE NOTE: it may look like I'm just trying to get the index of each span containing the letter but that is not the case. In practice (i.e.: outside the minimal case), the value I need in .on( 'click'...
and the index of each span will often be different.