我有两个图像,image_0 和 image_1,当单击每个图像时,我希望它显示一个警报,说明该图像的 ID。为此,我创建了一个数组来存储这些函数(这是必要的,因为我之前的问题: https://stackoverflow.com/questions/41003122/looping-in-jquery-only-remembers-last-iteration?noredirect=1#comment69215730_41003122 )。
下面的代码显示了我的尝试。但是,当我单击任一图像时,什么也没有发生。为什么?
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];
});
}
});
最佳答案
添加一个公共(public)类,创建一个处理程序,并使用this
的实例
<img class="image" id="image_0" src="http://placehold.it/350x150" width="300">
<img class="image" id="image_1" src="http://placehold.it/350x150" width="300">
JS:
$(".image").click(function() { alert(this.id) });
关于javascript - img.click() 函数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41019131/