1

I have a link like

<a href="#" id="foo" class="bar_link">blah</a>

I have many of these and the id value is an integer corresponding to a record in a database.

I want to create a click handler to pass the id attribute value for a specific link into a function whenever that link is clicked.

Here is what I have tried, but I am not having success.

$(".bar_link").live('click', barDetailsInit($(this).attr('id')));

What do you think? Thx!

istan
  • 1,297
  • 3
  • 21
  • 36
  • 2
    I would like to point out that `id` attributes cannot be integers. Consider using `name` instead. (http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html) – Doug Owings Jun 22 '11 at 23:09
  • Thanks, Doug! I did not know that. – istan Jun 22 '11 at 23:21

3 Answers3

4

This will work

$('.bar_link').live('click', function() { 
    barDetailsInit(this.id);
});
Šime Vidas
  • 163,768
  • 59
  • 261
  • 366
Variant
  • 16,291
  • 4
  • 37
  • 64
2

Oops, you forgot to wrap the click event in an anomymous method.

$(".bar_link").live('click', function() { barDetailsInit($(this).attr('id')); });

Your version would pull this as whatever the scope that the line is running in (probably "window").

Abishai Gray
  • 525
  • 2
  • 7
1

Try this instead:

$(".bar_link").live('click', function(event) {

    barDetailsInit($(this).attr('id')));

});

Basically you'll need to call your function from within the event callback, then at that point you have context and can call your function with the desired parameter.

Ben Everard
  • 13,254
  • 12
  • 63
  • 95