使用 jQuery 检索子按钮的特定父级

Retrieve a specific parent of child button using jQuery

本文关键字:按钮 jQuery 检索 使用      更新时间:2023-09-26

我有这个html结构(非常通用),div的id是通过一个创建顺序对象的函数动态添加的:

 <div id="mydiv1">
     <div> Stuff</div>
     <div>
        <button id="remove"></button>
     </div>
 </div>

"删除"按钮应该删除他所在的div,所以我必须检索div 的 id 才能做到这一点。我不知道怎么做。如何使用jQuery制作?谢谢

<form>
   <div id="mydiv1">
     <div> Stuff</div>
     <div>
        <button id="remove"></button>
     </div>
   </div>
   <div id="mydiv2">
     <div> Stuff</div>
     <div>
        <button id="remove"></button>
     </div>
   </div>
</form>

我试过了:

("#remove").click(function(event) {
    var id = event.target.id;
}

但结果是:"删除"而不是"mydiv1"或"mydiv2"

您应该使用 class 而不是 id 作为按钮(id应该是唯一的):

$('.remove').click(function() {
  $(this).closest('div[id^="mydiv"]').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <div id="mydiv1">
    <div>Stuff 1</div>
    <div>
      <button class="remove">REMOVE</button>
    </div>
  </div>
  <div id="mydiv2">
    <div>Stuff 2</div>
    <div>
      <button class="remove">REMOVE</button>
    </div>
  </div>
</form>

编辑:更新为OP发布的新代码

对于 mydiv2 更改按钮,如下所示:

$(".remove").click(function() {
    var id = $(this).data('id');
    $("#mydiv"+id).remove();
}
<button class="remove" data-id="2"></button>

使用 $(this).parent('div') 获取类型为 <div> 的第一个父节点

$("#remove").click(function(event) {
    var parent = $(this).parent('div');
    parent.remove();
}

编辑

因此,在您的

div中添加一个类,例如.divRow

<form>
    <div id="mydiv1" class="divRow">
       <div> Stuff</div>
       <div>
           <button id="remove"></button>
       </div>
    </div>
    <div id="mydiv2" class="divRow">
       <div> Stuff</div>
       <div>
           <button id="remove"></button>
       </div>
    </div>
</form>

在这种情况下,您的JavaScript将

$("#remove").click(function(event) {
    var parent = $(this).parent('.divRow'),
            id = parent.attr("id");
    alert(id);
    parent.remove();
}

尝试

$('.remove').click(function() {
  var id = $(this).parent().parent().attr('id');
  //This will give you the id
});

对于问题的下一部分,请尝试以下操作:

$(document).on('click','.remove',function() {
  var id = $(this).parent().parent().attr('id');
  //This will give you the id
});