我有两个图像,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">
Run Code Online (Sandbox Code Playgroud)
使用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];
});
}
});
Run Code Online (Sandbox Code Playgroud)
添加一个公共类,创建一个处理程序,并使用一个实例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">
Run Code Online (Sandbox Code Playgroud)
JS:
$(".image").click(function() { alert(this.id) });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |