14

我有一个 DIV,当我单击该 DIV 中包含的链接时,我想将其删除。这是我所拥有的:

<div id="clients-edit-wrapper">
    <div class="close-wrapper">
        <a href="#" class="close-div">Close</a>
    </div>
</div>

当我单击“关闭”时,我想clients-edit-wrapper被删除。我正在寻找一种方法来通过引用关闭链接的父 DIV 来做到这一点,在这种情况下,是clients-edit-wrapper.

任何帮助将不胜感激!


黄教的回答如下:

$('.close-div').click(function(){
   $(this).parent().parent().remove();
});

这仅在您要删除的元素是两个父元素时才有效。就我而言,这正是我所需要的。

4

8 回答 8

18

给定您的 html 标记

更新为 .on()

$('.close-div').on('click', function(){
    $(this).closest("#clients-edit-wrapper").remove();
});

具有更大的灵活性.closest,这使您可以选择拥有更多的父母或更少的父母。

https://api.jquery.com/closest/

对于集合中的每个元素,通过测试元素本身并向上遍历其在 DOM 树中的祖先来获取与选择器匹配的第一个元素。

编辑
(添加相关资源)
请参阅live()上的 jQuery 文档

从 jQuery 1.7 开始,不推荐使用.live() 方法。使用 .on() 附加事件处理程序。旧版本 jQuery 的用户应该使用 .delegate() 而不是 .live()。

据我所知,这是由于live().

于 2012-06-15T20:47:58.187 回答
9

这是一种解决方案:

$(".close-div").on("click", function(event) {
    $("#clients-edit-wrapper").remove();
    event.preventDefault();
});

要获取#clients-edit-wrapper相对于元素的.close-div元素,您可以使用其中一个parent().parent()closest使用 ID:

$(this).parent().parent().remove();                  // will do
$(this).closest("#clients-edit-wrapper").remove();   // the same

但是,最后一个没有意义,因为页面元素的 ID 应该是唯一的,并且不会有另一个#clients-edit-wrapper.

于 2012-06-15T20:47:06.540 回答
2
$(".close-div").click(function(){

    $("#clients-edit-wrapper").remove();

});
于 2012-06-15T20:47:32.700 回答
1

由于您将元素基于父元素,因此我鼓励事件委托:

$("#clients-edit-wrapper").on("click", ".close-div", function(e){
    e.preventDefault();
    $(e.delegateTarget).remove();
});
于 2012-06-15T20:48:42.523 回答
1
<div id="clients-edit-wrapper">
    <div class="close-wrapper">
         <a href="#" onclick="$('#clients-edit-wrapper').remove();" class="close-div">Close</a>
    </div>
</div>
于 2012-06-15T20:49:00.717 回答
1
$('#clients-edit-wrapper').find('.close-div').click(function(){
   $('#clients-edit-wrapper').remove();
});
于 2012-06-15T20:46:59.363 回答
1

你也可以用closest

$('.close-div').on('click', function(e) {
  e.preventDefault();
  $('#clients-edit-wrapper').remove();
});
于 2012-06-15T20:47:06.647 回答
-1
$('body').on('click','.close-div', function(){
  $(this).closest("#clients-edit-wrapper").remove();
});
于 2018-08-15T11:32:19.323 回答