我有两个表。
我想比较两个表,如果td
具有相同的类(例如 id-1 == id-1
( 我想在第一个td
从第一个table
第二个td
复制和替换到第二个table
。
$('.table1 tr td:first-child').each(function() {
var firstTableClass = $(this).attr('class');
$('.table2 tr td:first-child').each(function() {
if ($(this).attr('class') === firstTableClass) {
$(this).html($('.table1 tr td:last-child').html());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table1" border="1">
<caption>Table 1</caption>
<tr>
<td class="id-1">1</td>
<td>Name</td>
</tr>
<tr>
<td class="id-2">2</td>
<td>Name 2</td>
</tr>
</table>
<table class="table2" border="1">
<caption>Table 2</caption>
<tr>
<td class="id-1">1</td>
<td>2019</td>
</tr>
<tr>
<td class="id-2">2</td>
<td>2018</td>
</tr>
</table>
问题是仅在所有td
中复制第一个名称。
我希望表 2 有这个结果
<table class="table2" border="1">
<tr>
<td class="id-1">Name</td>
<td>2019</td>
</tr>
<tr>
<td class="id-2">Name 2</td>
<td>2018</td>
</tr>
</table>
有什么想法吗?
这是一个jsfiddle
提前感谢!
正如评论中提到的:问题是你总是在最内在的循环中抓住第一个table
的第一个tr
。
为每次迭代添加一个计数器并为tr
使用:eq()
选择器应该可以解决问题。
$('.table1 tr td:first-child').each(function() {
var firstTableClass = $(this).attr('class');
var i = 0;
$('.table2 tr td:first-child').each(function() {
if ($(this).attr('class') === firstTableClass) {
$(this).html($('.table1 tr:eq(' + i + ') td:last-child').html());
}
i++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table1" border="1">
<caption>Table 1</caption>
<tr>
<td class="id-1">1</td>
<td>Name</td>
</tr>
<tr>
<td class="id-2">2</td>
<td>Name 2</td>
</tr>
</table>
<table class="table2" border="1">
<caption>Table 2</caption>
<tr>
<td class="id-1">1</td>
<td>2019</td>
</tr>
<tr>
<td class="id-2">2</td>
<td>2018</td>
</tr>
</table>
https://jsfiddle.net/feonsa9c/<--在这里摆弄