I have an array of objects that I'm looping through to create DOM elements. The object I've defined has several properties I want to pass along to the resulting DOM element including a function "onclick_fn" so each result can handle that event as needed.
Everything is working fine except for passing though the function. I've tried quite a few things and I'm unable to figure this out. The function doesn't persist and is "undefined" when needed for the event.
I created a JSFiddle to illustrate the problem.
function run_me() {
console.log("make_array");
add_divs(make_array());
}
function make_array() {
var my_array = [];
my_first_obj = {
name: "ClickTheFirstOne",
age: 24,
callback_fn: function(div) {
$(this).append("clicked first");
}
};
my_array.push(my_first_obj);
my_next_obj = {
name: "ClickTheSecondOne",
age: 42,
callback_fn: function(div) {
$(this).append("clicked second");
}
};
my_array.push(my_next_obj);
return my_array;
}
function add_divs(my_array)
{
for (var i = 0; i < my_array.length ; i++) {
var new_div = document.createElement("div");
$(new_div).append("<div>" + my_array[i].name + ", " + my_array[i].age + "</div>");
$(new_div).click( function() { my_array[i].callback_fn(this); } );
$("#my_div").append(new_div);
}
}