简体   繁体   English

通过单击子元素获取父div ID

[英]Get parent div id by clicking on a child element

What I'm looking to do is remove the parenting div by ID after the button is clicked, to avoid closing all divs with the same class. 我想做的是单击按钮后按ID删除育儿div,以避免关闭具有相同类的所有div。 In my actual code, the user is able to append multiple divs to the screen on button click, and each is assigned it's own ID. 在我的实际代码中,用户可以在单击按钮时将多个div附加到屏幕上,并且为每个div分配了自己的ID。 Each has a boostrap button up top that should close the parent div only instead of having to create 12 separate functions (the limit of div placement for the user). 每个按钮顶部都有一个boostrap按钮,该按钮仅应关闭父div,而不必创建12个单独的函数(用户的div位置限制)。

HTML HTML

<div class='some classes' id='box1'>
<span class='btn btn-primary'>Close this div</span>
</div>
<div class='some classes' id='box2'>
<span class='btn btn-primary'>Close this div</span>
</div>

CSS CSS

#box {
  width:200px;
  height:200px;
  background:black;
}

JS JS

$(document).ready(function(){
  $('.btn').on('click',function(){
    var getParentID = $('.btn').parent().attr('id');
    $(getParentID).remove();
});
});

This is essentially all I was working with to try to get it to function. 实际上,这就是我试图使其正常运行的全部工作。 Any help is much appreciated! 任何帮助深表感谢!

Use $(this) instead of $('.btn') since you want to target the specific element 使用$(this)代替$('.btn')因为您要定位特定元素

var getParentID = $(this).parent().attr('id'); Once the id is available use jquery id selector to target the element ID可用后,请使用jquery id选择器定位元素

 $(document).ready(function() { $('.btn').on('click', function() { var getParentID = $(this).parent().attr('id'); $("#" + getParentID).remove(); }); }); 
 #box { width: 200px; height: 200px; background: black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='some classes' id='box1'> <span class='btn btn-primary'>Close this div</span> </div> <div class='some classes' id='box2'> <span class='btn btn-primary'>Close this div</span> </div> 

Note: The answer is specific to your question.Alternatively the parent div can be removed even without getting it's id 注意:答案是特定于您的问题的。或者,即使没有获得ID,也可以删除父div

What you want to do is to skip the jQuery and do it in pure javascript. 您想要做的是跳过jQuery,并使用纯JavaScript进行操作。

var parent = child.parentElement;
parent.parentElement.removeChild(parent);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM