I have two images, image_0 and image_1, and when each is clicked, I want it to display an alert saying the id of that image. To do this, I have created an array to store these functions (this was necessary because of my previous issue: https://stackoverflow.com/questions/41003122/looping-in-jquery-only-remembers-last-iteration?noredirect=1#comment69215730_41003122).
The code below shows my attempt. However, nothing happens when I click either image. Why?
HTML:
<img id="image_0" src="http://placehold.it/350x150" width="300">
<img id="image_1" src="http://placehold.it/350x150" width="300">
Javascript:
$(document).ready(function()
{
// The number of images shown
num_images = 2
// List of functions for each thumbnail click.
var image_click_functions = new Array(num_images);
// Define the function for when the thumbnail is clicked
function CreateImageClickFunction(image_id)
{
return function() { alert(image_id) };
}
// Loop through all images, and define the click functions
for (i = 0; i < num_images; i++)
{
image_click_functions[i] = CreateImageClickFunction(i);
image_id = "#image_" + i;
$(image_id).click(function()
{
image_click_functions[i];
});
}
});