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.

2
  • 2
    An immediate fix: 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 Commented Jul 15, 2013 at 16:27
  • @Ian Thanks! I would have spent ages figuring that out. Commented Jul 15, 2013 at 16:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.