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

时间:2015-03-10 11:55:41

标签: javascript html

我有这个html结构(很一般),div的id是动态添加的,由一个以这种方式创建顺序对象的函数:

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

按钮&#34;删除&#34;应该删除他所在的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;
}

但结果是:&#34;删除&#34;而不是&#34; mydiv1&#34;或&#34; mydiv2&#34;

4 个答案:

答案 0 :(得分:2)

您应该使用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发布的新代码

答案 1 :(得分:0)

使用$(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();
}

答案 2 :(得分:0)

尝试

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

答案 3 :(得分:0)

对于像这样的mydiv2更改按钮:

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