首页 > 解决方案 > 如何使用jquery从两个表中删除匹配的记录

问题描述

如果单击删除,我正在尝试从两个表中删除匹配的记录。这里匹配除了最后一列仅因为最后一列删除按钮。我的代码不起作用:如果我单击删除所有匹配的 tr 删除,但我想要在两个表中单击删除按钮的哪一行匹配行仅删除。我该怎么做?

代码:https ://jsfiddle.net/d4yzrtwn/3/

$(function(){
$('.remove').on('click', function(e){
    $('#T1 tbody tr').each(function(){
    var row = $(this);
    var left_cols = $(this).find("td").not(':last');
    $('#T2 tbody tr').each(function(){
        var right_cols = $(this).find("td").not(':last');
        if(left_cols.html() == right_cols.html()) { 
            $(this).closest('tr').remove();
         }
     });

     $(this).closest('tr').remove();

  });
  });
 });

标签: javascriptjquery

解决方案


比较基于所选行表的 html 内容与对应表。

选择是动态的,这意味着反之亦然,并限制删除不匹配的记录。

$(function() {
  $('.remove').click(function() {
    let clicked_row = $(this).closest('tr');
    let clicked_table = clicked_row.closest('table tbody').find('tr');
    clicked_table.each(function() {
      if (clicked_row.closest('table').attr('id') === 'T1') {
        opponent_table = $('#T2 tbody tr');
      } else {
        opponent_table = $('#T1 tbody tr');
      }
      opponent_table.each(function() {
        if ($(this).html() === clicked_row.html()) {
          $(this).remove();
          clicked_row.remove();
        }
      });

    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<table id="T1" border='1'>
  <thead>
    <tr>
      <th>First Name</th>
      <th>Middle Name</th>
      <th>Last Name</th>
      <th>Suffix</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>12</td>
      <td>34</td>
      <td>56</td>
      <td><span class="remove">Remove</span></td>
    </tr>
    <tr>
      <td>12</td>
      <td>84</td>
      <td>96</td>
      <td><span class="remove">Remove</span></td>
    </tr>
    <tr>
      <td>bat</td>
      <td>man</td>
      <td>11</td>
      <td><span class="remove">Remove</span></td>
    </tr>

  </tbody>
</table>
<br>
<table id="T2" border='1'>
  <thead>
    <tr>
      <th>First Name</th>
      <th>Middle Name</th>
      <th>Last Name</th>
      <th>Suffix</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>12</td>
      <td>34</td>
      <td>56</td>
      <td><span class="remove">Remove</span></td>
    </tr>
    <tr>
      <td>bat</td>
      <td>man</td>
      <td>11</td>
      <td><span class="remove">Remove</span></td>
    </tr>
    <tr>
      <td>james</td>
      <td>bond</td>
      <td>007</td>
      <td><span class="remove">Remove</span></td>
    </tr>
    <tr>
      <td>12</td>
      <td>34</td>
      <td>56</td>
      <td><span class="remove">Remove</span></td>
    </tr>
  </tbody>
</table>

jsfiddle在这里:https ://jsfiddle.net/debendraoli/qvy0dLfh/33/


推荐阅读