I have an array of contacts in a JSON object however the variable that displays in the .on('click'...)
event is always the last item in the JSON array.
The <a>
id is set correctly but the alert always returns the last contactID in the JSON array
Is there something in my code that is wrong....?
var theDIV = $('#1234DIV');
for (var i=0;i<theJSON.contacts.length;i++) {
var theContact = theJSON.contacts[i];
var contactID = theContact.contact_id;
var theLink = $('<a>',{
'id': 'Acontact_'+contactID,
'href':'javascript:;',
}).on('click', function(event) {
console.log(event);
console.log(contactID);
alert(contactID);
}).html(theContact.name_display);
theDIV.append(theLink);
}
Here is the JSON example:
{"result_count":2,"contacts":[{"contact_id":"508","name_display":"George Washington","flag_type":"contact","name_title":"","name_first":"George","name_last":"Washington"},"contact_id":"716","name_display":"Red","flag_type":"contact","name_title":"","name_first":"Red","name_last":"Shawshank"}]}