最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - what is the best practice of binding jQuery click event to each anchor tag on every row of a table - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 9

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.

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();
   }
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论