jQuery scope (?) issue with minimal case demo
HTML
<button id="btn">Debug</button>
<div class="target">
<span></span>
</div>
CSS
body { margin: 0; }
div span {
color: #0088CC;
cursor: pointer;
margin-right: 0.5em;
}
JavaScript
var phoneposition = 0;
/* Returns a jQuery HTML object */
function getHTML( input, option ) {
var html = $();
var phones =
[
{ phone: 'A', start: 0, end: 1 },
{ phone: 'B', start: 1, end: 2 },
{ phone: 'C', start: 2, end: 3 },
{ phone: 'D', start: 3, end: 4 }
];
/** Add the click event handler to each span**/
for ( var i = 0; i < phones.length ; i++ ) {
(function(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:' , i );
})
html = html.add( span );
}(i));
}
return html;
}
$(document).ready(function() {
$( '#btn' ).click(function(event) {
var html = getHTML( 'some text', 0 );
$( "div.target > span" ).replaceWith( html );
});
});