Q:

Adding DIVs dynamically and attaching events

I'm attaching some DIVs dynamically in JQuery and want to attach each one a click event, this is how I do it
for (var i=0; i<CAItems.length; i++)
    {
        //alert(i);
        $('#UserWorldItems').append(
            $("<div id='ContextItm" + i + "' class='UserItem'><div class='UserItemBox'>" + 
                CAItems[i].Context + "</div><div class='UserItemBox AddPaddingToItem'>" + 
                CAItems[i].Action + "</div></div>").on("click" , function() { alert(i); } )
        );
    }

The DIVs are created but the function that is fired when clicking any of the new divs results in an alert saying "11" (11 is the last value of i). How can I resolve this that each div will show an alert with the right index? (0,1,2,3....11)

A:

You must to create a function with a param i to create the scope, and return the function you want to execute when the click is done. See that you are executing an anonymous function with param i that is the value of the i from the loop. Like it is a copy the alert will have the correct value. In your case, the for ends with the last value and when you clicked you saw always the same because you was asking for the value of i, now you have a new variable, and a different scope for function.
for (var i=0; i<CAItems.length; i++)
{
    //alert(i);
    $('#UserWorldItems').append(
        $("<div id='ContextItm" + i + "' class='UserItem'><div class='UserItemBox'>" + 
            CAItems[i].Context + "</div><div class='UserItemBox AddPaddingToItem'>" + 
            CAItems[i].Action + "</div></div>").on("click" , function (i) { return function() { alert(i); }; }(i) )
    );
}

