1

Here is a jsfiddle of the problem.

Clicking on "Lizard" should show a picture of a lizard in both cases.

When replacing the "+ entries[index] +" with 1 and 6 respectively, everything works fine. When doing it with a loop, it does not work anymore.

I have no idea why.

MacBryce
  • 133
  • 1
  • 3
  • 14
  • 2
    An immediate fix: http://jsfiddle.net/7KnZd/1/ . By the time the event handlers are executed (when a `click` event occurs), the loop has completed...meaning that `index` refers to the last item in the loop, so `entries[index]` inside the handlers won't refer to what you expect. My example captures the value of `index` by creating a new scope (calling `handleItem`) so that all references to `index` inside the handlers will be the specific point in the loop – Ian Jul 15 '13 at 16:27
  • @Ian Thanks! I would have spent ages figuring that out. – MacBryce Jul 15 '13 at 16:57

1 Answers1

1

Your error is that you expect entries[i] to have a vaule inside the clickevent.

$("#"+ entries[1] +"-choice-C").bind("click", function() {
    $("#"+ entries[1] +"-lizard").show();
});

The value of entries[i] when you click will be undefined, because the value if i will be 2 (the same as the length of the array).

What you need is a closure to keep the value of i, and here is an example:

var items = ["a","b", "c"];
var displayItem = function (i) {
    window.setTimeout(function () {
        alert(items[i]);
    }, 100);
}

for (var i = 0; i < items.length; i++) {
    displayItem(i);
}

For the code that soves your problem, got to the feedle that @Ian commented.

Community
  • 1
  • 1
Kaizo
  • 4,155
  • 2
  • 23
  • 26