What is the best practice of binding a jQuery click event to each anchor tag in each row of a table

There is a grid (only the html table) in which users are listed, and you can delete a specific user by clicking the delete link. The usual way 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 bind the click event to the link in an unobtrusive way. I mean that I do not want to specify the javascript method inside the tag. I'm not sure if this is the best way to achieve this with jQuery, by binding multiple multiple anchor tags with parameter passing.

+3
source share
2 answers

You can use the method delegate()in 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());
});

, .

+9

:

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

Source: https://habr.com/ru/post/1773624/


All Articles