javascript - 如何使用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();
});
});
});
解决方案
比较基于所选行表的 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/
推荐阅读
- linux - 如何找到一个文件,然后将该文件及其内容存储为变量,以便对原始文件运行操作?
- html - 为标签云创建路标样式大纲
- python - Athena 上的 AWS lambda 查询不返回任何内容
- powershell - 如何更新特定 cmdlet 的帮助?
- cordova - 为什么使用 apache cordova 为 android 签名应用程序失败?
- c - 为什么具有递减阶段的冒泡排序不起作用?
- python - 如何在 3D 列表中弹出元素?
- python - 如何在图形(django python)中循环[('A',1),('B',2),('C',4)]这种类型的数据?
- flutter - 如何在flutter中添加ExpansionPanels之间的间隙?
- python - 根据日期列差异过滤熊猫数据框