What is the correct way to bind events in jQuery?
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_ele开发者_如何学Goments_id)"
right in the list item.
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.
}):
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() );
});
You can also use .bind
E.g.
$('#item').bind("click", function() { do something; });
$(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.
});
});
精彩评论