我正在关注来自 jquery append and remove dynamic table row ( http://jsfiddle.net/samliew/3AJcj/2/ )
我已经整理好了我的 table 。
但是删除功能不起作用,我如何更改这段代码?
我无法理解 $(this).parent().parent().remove();
代码。
$(document).ready(function(){
$(".addCF").click(function(){
$("#addTg").after('<tr><td class="tg-yw4l" ><input type="text"></td><td class="tg-yw4l" colspan="2" ><input type="text"></td><td class="tg-yw4l" ><input type="text"></td><td><a href="javascript:void(0);" class="remCF" >Remove</a></td></tr>');
});
$("#addTg").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="tg">
<tr>
<td class="tg-mtwr">DATE</td>
<td class="tg-mtwr" colspan="2" >CONTENTS</td>
<td class="tg-mtwr">PRICE</td>
<td class="tg-mtwr">BUTTON</td>
</tr>
<tr id="addTg">
<td class="tg-yw4l" ><input type="text"></td>
<td class="tg-yw4l" colspan="2" ><input type="text"></td>
<td class="tg-yw4l" ><input type="text"></td>
<td class="tg-yw4l"></td>
</tr>
<tr>
<td colspan="5" style="border:0px solid #fff;">
</td>
</tr>
</table>
<button onclick="myFunction()" class="addCF" >Add</button>
最佳答案
动态添加的元素不在 #addTg
中,它是该元素的同级元素。因此,使用父表类选择器更改选择器。
在处理程序中 this
指的是被点击的 dom 对象和 parent()
方法用于获取元素的父级。您可以使用 closest()
简化它 通过向上遍历其祖先来检索元素的方法。
虽然 myFunction
没有在您的代码中定义,所以从按钮中删除 onclick="myFunction()"
,这在这里不是必需的。
$(document).ready(function() {
$(".addCF").click(function() {
$("#addTg").after('<tr><td class="tg-yw4l" ><input type="text"></td><td class="tg-yw4l" colspan="2" ><input type="text"></td><td class="tg-yw4l" ><input type="text"></td><td><a href="javascript:void(0);" class="remCF" >Remove</a></td></tr>');
});
$(".tg").on('click', '.remCF', function() {
$(this).closest('tr').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="tg">
<tr>
<td class="tg-mtwr">DATE</td>
<td class="tg-mtwr" colspan="2">CONTENTS</td>
<td class="tg-mtwr">PRICE</td>
<td class="tg-mtwr">BUTTON</td>
</tr>
<tr id="addTg">
<td class="tg-yw4l">
<input type="text">
</td>
<td class="tg-yw4l" colspan="2">
<input type="text">
</td>
<td class="tg-yw4l">
<input type="text">
</td>
<td class="tg-yw4l"></td>
</tr>
<tr>
<td colspan="5" style="border:0px solid #fff;">
</td>
</tr>
</table>
<button class="addCF">Add</button>
关于javascript - 如何删除表动态行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38936744/