删除具有类名的元素的父级

时间:2018-10-15 13:09:51

标签: jquery

为什么没有通过单击按钮来删除.hor

$('.btn').click(function() {
  $('.delact').parent('.hor').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='hor'>
  <div class='divname'>lorem</div>
  <div class='inpwrap'>
    <input type='text' class='inpass' data-id=2 value='code323'>
    <div class='btndel delact' data-id=2 title='DELETE'>x</div>
  </div>
</div>

<button class='btn'>CLICK</button>

2 个答案:

答案 0 :(得分:3)

您在这里寻找的是.closest()方法,而不是.parent()

.parent()中的可选参数仅过滤直接父级:

  

.parent([selector])
  返回:jQuery
  说明:获取   当前匹配元素集中的每个元素(可选)   被选择器过滤。

$('.btn').click(function() {
  $('.delact').closest('.hor').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='hor'>
  <div class='divname'>lorem</div>
  <div class='inpwrap'>
    <input type='text' class='inpass' data-id=2 value='code323'>
    <div class='btndel delact' data-id=2 title='DELETE'>x</div>
  </div>
</div>

<button class='btn'>CLICK</button>

答案 1 :(得分:0)

尝试

$('.delact').closest('.hor').remove();使用closest代替parent

$('.btn').click(function() {
  $('.delact').closest('.hor').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='hor'>
  <div class='divname'>lorem</div>
  <div class='inpwrap'>
    <input type='text' class='inpass' data-id=2 value='code323'>
    <div class='btndel delact' data-id=2 title='DELETE'>x</div>
  </div>
</div>

<button class='btn'>CLICK</button>