1

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);
    }
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Mark Evans
  • 129
  • 1
  • 10
  • 1
    This is the very common issue of your `for` loop index variable is not still the same value, some time later when your event handler fires so `[i]` will be pointing past the end of your array rather than at the element you want. There are many dup questions/answers about this topic. I will find one shortly. – jfriend00 May 12 '14 at 21:40
  • Other related questions: http://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue, http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example, http://stackoverflow.com/questions/4091765/assign-click-handlers-in-for-loop – Felix Kling May 12 '14 at 22:44

0 Answers0