Using on() to handle child events
This example shows a more efficient way to handle click events for <tr> elements within a table.
HTML
<table id="CustomersTable" style="width:300px">
<tr>
<td>John Doe</td>
<td>Phoenix</td>
</tr>
<tr>
<td>Jane Doe</td>
<td>Phoenix</td>
</tr>
<tr>
<td>Johnny Doe</td>
<td>Phoenix</td>
</tr>
<tr>
<td>Ted Doe</td>
<td>Las Vegas</td>
</tr>
</table>
CSS
body {
cursor:pointer;
font-size:14pt;
}
.even {
background-color:#02027a;
color:white;
}
.toggle {
background-color: green;
color: white;
}
JavaScript
var $table = $('#CustomersTable');
$('tr:even', $table).addClass('even');
$table.find('tr').hover(function() {
$(this).toggleClass('toggle');
});
//This code provides an efficient way to handle click events
//when you have multiple children in a parent
$table.on('click', 'tr', function() {
//alert($(this).html());
alert('clicked row');
});