通过类名称删除父div-jQuery [英] Remove parent div by class name - jquery

查看:56
本文介绍了通过类名称删除父div-jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个删除链接,该链接将删除我页面上的当前评论.它使用ajax更改数据库,成功后,我要删除注释所在的div.页面上的每个注释如下:

I have a remove link that will remove the current comment on my page. It uses ajax to change the database and upon success, I want to remove the div the comment resides in. Each comment on the page looks like this:

<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返回成功后,我不知道如何删除它.我已经尝试过

I can't figure out how to remove the div once it has returned success. I've tried

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

也没有运气. $(this)是指定位标记,所以定位标记的parent()应该是<div class="aComment">正确吗?

and no luck. $(this) refers to the anchor tag so parent() of the anchor should be the <div class="aComment"> right?

推荐答案

在Ajax回调中,this并不引用锚元素,但是即使引用了锚元素,.parent()方法也会返回 immediate 父元素,即span元素,而不是div.

Within your Ajax callback this does not refer to the anchor element, but even if it did, the .parent() method returns the immediate parent, i.e., the span element, not the div.

假设您对锚点有参考,您可以说:

Assuming you have a reference to the anchor, you can say:

 $theAnchor.parent().parent().remove();  // get a's parent's parent

...但是当然这有点脆弱,因为如果以后更改html结构,则必须将代码更改为.因此,最好使用.closest()在树中搜索到与以下元素匹配的最接近的祖先元素:

...but of course that is kind of brittle because if you later change the html structure you have to change the code to. So it is better to use .closest() to search up the tree to the nearest ancestor element that matches:

$theAnchor.closest("div").remove();

您没有显示点击处理程序,但是需要这样:

You don't show your click handler, but it'll need to be something like this:

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

这篇关于通过类名称删除父div-jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆