views:

138

answers:

4

For example in php I have a list of clients:

foreach($clients as $client)
    echo '<li id="client_'.$client->id.'">' . $client->name . '</li>';

What is the correct way to bind a click event to each list item w/o using

onclick="my_function(the_elements_id)"

right in the list item.

+4  A: 

assuming you have a ul with id="client_list"

$("#client_list li").click(function()
{
    var myid = $(this).attr("id"); // the clicked on items id
    // do your thing here.

}):
John Boker
awesome, thank you
ws0x9
`$(this).attr("id")` is not as efficient as `this.id`. Every HTML object will have an `id` attribute; you don't need jQuery to soften this up for you.
MightyE
okay, thanks for the help
ws0x9
A: 
$(document).ready(function(){

    $("li).click(function(){
        var id = $(this).attr("id");
        your_function(id); //The function you want to run with the object's ID as a parameter.
    });

});
BraedenP
+1  A: 

You can also use .bind

E.g.

$('#item').bind("click", function() { do something; });
Jimmeh
+4  A: 

And very cool "live" way of binding for all current and future matched elements. This comes in handy if you use Ajax, and have to re-bind event to let's say image that you fetch via ajax.

More info @ http://docs.jquery.com/Events/live#typefn

$("p").live("click", function(){
  alert( $(this).text() );
});
epitka
Thanks! New to jQuery and I appreciate the help.
ws0x9
Yes live is great if there's any chance of the markup being changed on the fly. It's an implementation of delegation.
Nosredna
Used it today. Very useful. Thanks for the guidance.
ws0x9