[英]Remove parent element and all children
因此,我有一个表,每当提交按钮时,它就会向该表添加一个包含4列的行,然后在每行中放置一个删除按钮。 我的目的是能够删除整个行,但是当我按下它时,它只会删除按钮。 如何删除整行?
$(this).parent().remove()
我试过了,但它不起作用,因为td直接位于tr内,所以它应该访问tr并删除它,但该行仍然存在。
您要选择最接近的tr
元素,而不是直接父元素。 没有看到您的事件绑定,我猜$(this)
是按钮,而$(this).parent()
是<td>
。 相反,您应该尝试:
$(this).closest('tr').remove();
或者,如果可以保证tr>td>button
的特定层次结构,则可以使用:
$(this).parent().parent().remove();
我强烈不鼓励使用后一种格式,因为它与HTML的结构紧密相关。 如果您的HTML开头为:
<tr>
<td>
<button>Example</button>
</td>
</tr>
后来更改为:
<tr>
<td>
<div class="wrapper">
<button>Example</button>
</div>
</td>
</tr>
使用closest('tr')
将继续工作,但使用parent().parent()
将中断。
与您未触发事件的第二个问题有关。 如果您要通过$('.foo button').click(removeRow);
绑定事件, (其中.foo
与table
元素匹配),该事件将不适用于新创建的button
元素。 相反,您应该使用on
的事件委托形式(或者,如果使用的是旧版jQuery,则只需delegate
):
$('.foo').on('click', 'button', removeRow);
这会将事件绑定存储在table
元素上,并在调用回调时,将检查触发指定事件的元素是否与第二个参数(在本例中为'button'
)中指定的选择器匹配,它会以匹配的元素作为上下文触发指定的处理程序(在本例中为removeRow
)(在处理程序中, this
仍将指向button
元素)。
$(this).closest('tr').remove();
我假设您的代码如下所示:
<table>
<tr>
<td>Column</td>
<td><button></button></td>
</tr>
</table>
因此,您的$(this).parent()
是<td>
,而不是<tr>
。 您需要另一个parent()
:
$(this).parent().parent().remove();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.