Trying to get the numerical value of the current button that’s being called from an array so I can display an image and description from another array based on bNames array number.
i doesn’t seem to work.
Trying to get images[i] and descriptions[i] to show based on the numerical value of bNames.
var bNames = ["#button01","#button02","#button03"];
var images = ["image01.png","image02.png","image03.png"];
var descriptions = ["And a one","And a two", "And a three"];
for (var i=0; i<bNames.length; i++){
$(bNames[i]).click(function(e) {
$("#image").html("<img src=images/" + images[i] + " />");
$("#desc").html(descriptions[i]);
});
}
Any help is greatly appreciated, thanks!
The problem you are having is described in this question. Also see JavaScript loop closures for more information. Essentially, you are always using the last value that is held by
i.Something like this should do the trick:
Also from that question, you could do this instead: