按类名删除父div - jquery

时间:2012-03-01 22:32:48

标签: jquery

我有一个删除链接,会删除我页面上的当前评论。它使用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)是指锚标记,因此锚点的parent()应该是<div class="aComment">权利吗?

5 个答案:

答案 0 :(得分:4)

使用closest()

$(this).closest(".aComment").remove();

Example

a标记的父级是span。您要删除的divspan的父级。

使用它的原因仅仅是因为它比使用parent()两次更方便。

答案 1 :(得分:4)

在你的Ajax回调this中没有引用锚元素,但即使这样做,.parent()方法也会返回 immediate 父元素,即span元素,而不是div。

假设您有对锚点的引用,您可以说:

 $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();
   });
});

答案 2 :(得分:2)

应该是

$(this).parent().parent().remove();

答案 3 :(得分:0)

最好通过在代码中为注释设置ID来解决此问题。

例如:

<div class="aComment" data-comment-id="5">

然后将此ID与您的AJAX请求和响应一起使用。

多一点工作,但它更健壮(IMO)

答案 4 :(得分:0)

如果您尝试通过点击删除它:

$(".aComment a").on('click', function(){
    $(this).closest(".aComment").remove();
});

http://jsfiddle.net/gaQuu/

相关问题