jquery - 按类名删除父 div - jquery

标签 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)引用 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/

相关文章:

jquery - 如何为 jQuery 实例应用类型保护?

VS2012 中的 jQuery 智能感知

javascript - 我在我的网站中添加了在线 JavaScript。如何更改由该 JavaScript 添加的网页中的 HTML?

javascript - 定义 JQuery 函数

jquery如何每5秒触发相同的事件

javascript - JQuery:如何替换两个特定部分之间的属性部分?

javascript - 将 imagegrabscreen php 函数包含到按钮 onclick 中,无需刷新页面

javascript - 创建一个非常简单的 jQuery 插件,不工作

jquery - 停止并重播动画以相同的速度导致结果看起来很慢

javascript - 如何从脚本标签中提取字符串数据,其中脚本没有任何 id?