我有一个表,在其中动态添加和删除行.按"删除"时,我想删除整行.这可以很好地处理已经存在的行,但是当对新行使用相同的函数时,它会删除所有内容.
如何仅删除新创建的行,而不是所有行?
我试着用find()
来找到tr
,但没有用.
$("#addRow").click(function() {
$("#table").append(
`<tr>`,
`<td></td>`,
`<td></td>`,
`<td></td>`,
`<td></td>`,
`<td></td>`,
`<td class="remove"><button>Remove</button></td>`,
`</tr>`
);
$('.remove button').on('click', function() {
removeRow($(this))
});
})
$('.remove button').on('click', function() {
removeRow($(this))
});
function removeRow(row) {
row.parent().parent().remove();
}
#table {
width: 80%;
margin-left: auto;
margin-right: auto;
}
#table td {
width: 20%;
border: solid 1px black;
}
#table .remove {
border: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="remove"><button>Remove</button></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="remove"><button>Remove</button></td>
</tr>
</table>
<p><button id="addRow">Add a new row</button></p>