2010-08-05 72 views
0

我有一个呈现的HTML表格与图像按钮,我可以用它来取消,看起来像一个项目:jQuery的图像按钮新手问题

Product ID  Product  Qty  Cancel 
12345   Widget A  1   ID=ImageButton-12345 Class=ImageButtonList 
23456   Widget B  1   ID=ImageButton-23456 Class=ImageButtonList 
34567   Widget C  1   ID=ImageButton-34567 Class=ImageButtonList 

我想什么做的是要经过在各项目ImageButtonList类,并找出哪个图像按钮被点击。图像按钮本身(在PHP中)标记为HTML,如:

<img src="/images/cancel_btn.jpg" class="ImageButtonList" id="ImageButton-12345"> 

这是类似jQuery的可能吗?我相信它必须是,因为我已经看到遍历属于一个类的所有项目的样本。也许沿线的东西:

$('.ImageButtonList').each(function() { 
    var element = $(this); 

    // Here's where I'm stuck 
}); 

我需要注册某种点击事件,所以我可以把它关闭?

回答

2

无需使用each,你可以找出哪些人得到了点击这样的:

$('.ImageButtonList').click(function(){ 
    alert('I was clicked, my id is ' + $(this).attr('id')); 
}); 

更多信息:

1
$('.ImageButtonList').click(function() { 
    // This will bind to all buttons 
    alert('You clicked me!'); 
}); 
1
var when_img_clicked = function() { 
    var element = $(this);  
    // "this" is the img element that is clicked. 
    clicked_id = $(this).attr('id'); 
    // Separate the actual id from clicked_id 
}; 
$('.ImageButtonList').click(when_img_clicked); 
0

我会建议的点击处理程序附加表本身,如果可能的话。因此,您不必遍历所有ImageButton,并且每个按钮只有一个事件处理程序,而不是一个。被点击的按钮然后可通过event.target

$('#table').click(function(){ 
    alert(event.target.id + ' was clicked'); 
});