我正在尝试使用以下代码启用/从表中添加/删除行:
脚本:
$(document).ready(function() {
$('#btnAdd').live('click', function() {
var name = $('#txtName').val();
var name2 = $('#txtName2').val();
$("#tbNames tr:last").append("<tr><td>" + name + "</td><td>" + name2 + "</td><td><simg ssrc='delete.gif' class='delete' height='15' /></td></tr>");
});
$('#tbNames td img.delete').live('click',function() {
$(this).parent().parent().remove();
});
});
HTML
<input id="txtName" type="text" />
<input id="txtName2" type="text" />
<input id="btnAdd" type="button" value="Add" />
<table id="tbNames" >
<tr>
<td>Name</td>
<td>Name2</td>
<td>Delete</td>
</tr>
<tr>
<td>Bingo</td>
<td>Tingo</td>
<td><simg ssrc="Delete.gif" height="15" class="delete" /></td>
</tr>
</table>
添加工作正常,但删除没有。
删除所点击后面的所有动态添加的行。
答案 0 :(得分:1)
我将添加功能从“追加”更改为“后”
$("#tbNames tr:last").after("<tr><td>" + name + "</td><td>" + name2 + "</td><td><img src='delete.gif' class='delete' height='15' /></td></tr>");
并更正了标记因为它说“simg”而不是“img”
所以强制解决方案是
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').live
('click',
function() {
var name = $('#txtName').val();
var name2 = $('#txtName2').val();
$("#tbNames tr:last").after("<tr><td>" + name + "</td><td>" + name2 + "</td><td><img src='delete.gif' class='delete' height='15' /></td></tr>");
}
);
$('#tbNames td img.delete').live('click',function() { $(this).parent().parent().remove(); });
}
);
</script>
<input id="txtName" type="text" />
<input id="txtName2" type="text" />
<input id="btnAdd" type="button" value="Add" />
<table id="tbNames" >
<tr>
<td>Name</td>
<td>Name2</td>
<td>Delete</td>
</tr>
<tr>
<td>Bingo</td>
<td>Tingo</td>
<td><img src="Delete.gif" height="15" class="delete" /></td>
</tr>
</table>
答案 1 :(得分:1)
您要将TR附加到TR,它应该附加到表的tbody(或表)。或.after()
TR。
$("#tbNames tbody").append("<tr><td>" + name + "</td><td>" + name2 + "</td><td><img src='delete.gif' class='delete' height='15' /></td></tr>")
此外,您应该指定您要查找的父项.closest()
使这很容易:
$("#tbNames td img.delete").live('click', function() {
$(this).closest('tr').remove();
});