简体   繁体   English

无法删除()行append()到表

[英]Cannot remove() a row append() to a table

I have a table with several rows () and I use jQuery append() to add one more row to the table. 我有一个包含多行()的表,我使用jQuery append()向表中添加一行。 Then I try to delete that row with remove(), which is working fine with the original rows, and fail. 然后我尝试使用remove()删除该行,该行与原始行一起正常工作,并且失败。

Please help. 请帮忙。 Thanks. 谢谢。

<table id="mybbbb" border="1" style="width:300px"><tbody>
    <tr><td>some text</td><td><div class="linksd">delete</div></td></tr>
    <tr><td>some text</td><td><div class="linksd">delete</div></td></tr>
    <tr><td>some text</td><td><div class="linksd">delete</div></td></tr>
    <tr><td>some text</td><td><div class="linksd">delete</div></td></tr>
</tbody></table>

<div id="addRow">add row</div>

<script>
jQuery("#addRow").click(function(event){
    event.preventDefault();
    jQuery("#mybbbb > tbody:last").append("<tr><td>more text</td><td><div class='linksd'>delete</div></td></tr>");
});

jQuery(".linksd").click(function(event){
            event.preventDefault();
            jQuery(this).parent().parent().remove();
            return false;
});
</script>

Your problem is that the newly created rows are not present in the DOM when the Javascript event listeners are assigned. 您的问题是,在分配Javascript事件侦听器时,新创建的行不存在于DOM中。

For jQuery 1.6 (as used in your fiddle) you can use live to listen past the original DOM creation point: 对于jQuery 1.6(在您的小提琴中使用),您可以使用live来听取原始DOM创建点:

$('.linksd').live('click', function(event){

And for more modern versions of jQuery ( live is deprecated now) you should use the on delegation: 而对于jQuery的更现代的版本( live现在已经过时),你应该使用on授权:

$(document).on('click', '.linksd', function(event){

Examples in the fixed fiddle and change the jQuery version to see. 固定小提琴中的示例并更改jQuery版本以查看。

There is no default behaviour for clicking on a div. 单击div没有默认行为。

Remove event.preventDefault(); 删除event.preventDefault(); and return false from your code like this, works for me. 并从这样的代码中return false ,对我有用。

jQuery(".linksd").click(function(event){   
    jQuery(this).parent().parent().remove();   
});

Demo : jsfiddle 演示: jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM