我有一个删除链接,它将删除我页面上的当前评论。它使用ajax来更改数据库,成功后,我想删除评论所在的div。页面上的每个评论如下所示:
<div class="aComment">
<span class="commentTitle">Posted by xxx at xxx - <a href="javascript:void(0)" class="deleteComment" data-commentid="anID"><img src="resources/images/delete_comment.png" title="Remove this comment" /></a></span>
<span class="commentText">comment text here</span>
</div>
我不知道如何在 div 返回成功后将其删除。我试过了
$(this).parent().remove();
但运气不好。 $(this)
引用 anchor 标记,所以 parent()
anchor 的应该是 <div class="aComment">
对吗?
最佳答案
在 Ajax 回调中 this
并不引用 anchor 元素,但即使引用了,.parent()
方法也会返回立即 父级,即 span 元素,而不是 div。
假设您有对 anchor 的引用,您可以说:
$theAnchor.parent().parent().remove(); // get a's parent's parent
...但是这当然有点脆弱,因为如果您稍后更改 html 结构,则必须更改代码。因此,最好使用 .closest()
在树中搜索匹配的最近的祖先元素:
$theAnchor.closest("div").remove();
您不显示点击处理程序,但它需要是这样的:
$(".aComment a").click(function() {
// keep a reference to the clicked a element for use
// in the ajax callback
var $theAnchor = $(this);
$.ajax(/* your ajax parameters here */, function() {
$theAnchor.closest("div").remove();
});
});
关于jquery - 按类名删除父 div - jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9525248/