Accepted answer

This is a closure issue. The problem is here:

for (var index = 0; index<5; index++) {
    items.push({text: "items "+index, onclick: function() {

In each iteration, you are setting the value of onclick to be a function which alerts index. However, the index variable within each of these functions are all bound to the one index variable declared outside the function. And the value of index that they will actually use by the time the function runs is the final value of index, which is 5.

In order to fix this, you can use an IIFE (Immediately-Invoked Function Expression) wrapper to pass each value of index into the anonymous function as a new variable i whose value won’t change as index changes.

for (var index = 0; index<5; index++) {
    items.push({text: "items "+index, onclick: (function(i) {
        return function(){

In other words, the wrapper function executes immediately and returns a new function which behaves like your original function except that it is not bound to the index iterator.

Updated fiddle

Related Query

More Query from same tag