开发者

jQuery image button newbie question

I have a rendered HTML table with an image button that I can use to cancel an item that looks like:

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

What I would like to do is go through each item in the ImageButtonList class and find out which image button was clicked. The image button themselves (in PHP) are marked up in HTML like:

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

Is something like this possible with jQuery?开发者_运维问答 I'm sure it has to be, because I've seen samples that iterate through all of the items that belong to a class. Maybe something along the lines of:

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

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

Would I need to register some sort of click event so I can pull this off?


No need to use each, you can find out which of them got clicked like this:

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

More Info:

  • .click()
  • .attr()


$('.ImageButtonList').click(function() {
    // This will bind to all buttons
    alert('You clicked me!');
});


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 );


I would suggest to attach the click-handler to the table itself, if possible. So you won't have to traverse over all the ImageButtons and you have only one event handler instead of one for each button. The clicked button would then be accessible by event.target

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜