There is a grid (just html table) that lists users and you can delete a specific user by clicking on delete link. The usual way I do is
<% foreach (var user in Model.Users) {%>
<tr >
<td align="right"><%= user.Name %></td>
<td><%= user.Level %></td>
<td align="center">
<a href="#" onclick="return deleteUser('<%= user.Name %>');">
<%= Html.Image("trash.gif") %>
</a>
</td>
</tr>
<% )%>
but I want to attach click event to the link in a non-obtrusive way. I mean, I do not want to specify javascript method inside the tag. I am not sure what is the best way to achieve it with jQuery, binding multiple multiple anchor tags with parameter passing.
There is a grid (just html table) that lists users and you can delete a specific user by clicking on delete link. The usual way I do is
<% foreach (var user in Model.Users) {%>
<tr >
<td align="right"><%= user.Name %></td>
<td><%= user.Level %></td>
<td align="center">
<a href="#" onclick="return deleteUser('<%= user.Name %>');">
<%= Html.Image("trash.gif") %>
</a>
</td>
</tr>
<% )%>
but I want to attach click event to the link in a non-obtrusive way. I mean, I do not want to specify javascript method inside the tag. I am not sure what is the best way to achieve it with jQuery, binding multiple multiple anchor tags with parameter passing.
Share Improve this question edited Nov 8, 2010 at 14:20 John Farrell 24.7k10 gold badges81 silver badges112 bronze badges asked Nov 8, 2010 at 13:59 Andrew ChaaAndrew Chaa 6,3883 gold badges48 silver badges33 bronze badges2 Answers
Reset to default 9You can use the delegate()
method on the table:
$('#tableId').delegate('a', 'click', function(e) {
e.preventDefault();
// get the user name
deleteUser($(this).closest('tr').children(':first').text());
// or give the cell that contains the name a class
// deleteUser($(this).closest('tr').children('.name').text());
});
This way, you only register one event handler.
For performance and optimization you can attach the click handler to that table:
<table id="grid">
<% foreach (var user in Model.Users) {%>
<tr >
<td class="name"><%= user.Name %></td>
<td><%= user.Level %></td>
<td align="center">
<a href="#" class="delete">
<%= Html.Image("trash.gif") %>
</a>
</td>
</tr>
<% )%>
</table>
$('#grid').click(function(e){
var source = $(e.target);
if(source.is('.delete')){ //or source.hasClass('delete')
var user = source.closest('tr').find('td.name').text();
deleteUser(user);
e.preventDefault();
}
});