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.

4

1 回答 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.

于 2013-07-15T16:38:13.600 回答