将jQuery click事件绑定到表的每一行上的每个锚标记的最佳做法是什么 [英] what is the best practice of binding jQuery click event to each anchor tag on every row of a table
本文介绍了将jQuery click事件绑定到表的每一行上的每个锚标记的最佳做法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个列出用户的网格(只是html表),您可以通过单击删除链接删除特定用户。我通常的做法是
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>
<% )%>
但我想以非突兀的方式将点击事件附加到链接。我的意思是,我不想在标签内指定javascript方法。我不确定用jQuery实现它的最佳方法是什么,用参数传递绑定多个多个锚标签。
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.
推荐答案
你可以使用 delegate()
方法table:
You 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.
这篇关于将jQuery click事件绑定到表的每一行上的每个锚标记的最佳做法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文