我正在努力删除子div除了每个父div中的最后一个div与同一个类,我的代码结构如下所示用我的Java脚本删除子div名称重复div:
$('.repeatable').on('click', '.close-repeating-div', function(e) {
e.preventDefault();
var countdiv = $('.repeatable').children('.repeating-div').length;
if (countdiv > 1) {
$(this).closest('.repeating-div').remove();
}
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js" integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<div class="repeatable">
<div class="repeating-div">
<input type="text" class="form-control">
<a href="#" class="btn close-repeating-div form-control"><i class="fa fa-remove" aria-hidden="true"></i></a>
</div>
<div class="repeating-div">
<input type="text" class="form-control">
<a href="#" class="btn close-repeating-div form-control"><i class="fa fa-remove" aria-hidden="true"></i></a>
</div>
<div class="repeating-div">
<input type="text" class="form-control">
<a href="#" class="btn close-repeating-div form-control"><i class="fa fa-remove" aria-hidden="true"></i></a>
</div>
</div>
<div class="repeatable">
<div class="repeating-div">
<input type="text" class="form-control">
<a href="#" class="btn close-repeating-div form-control"><i class="fa fa-remove" aria-hidden="true"></i></a>
</div>
<div class="repeating-div">
<input type="text" class="form-control">
<a href="#" class="btn close-repeating-div form-control"><i class="fa fa-remove" aria-hidden="true"></i></a>
</div>
<div class="repeating-div">
<input type="text" class="form-control">
<a href="#" class="btn close-repeating-div form-control"><i class="fa fa-remove" aria-hidden="true"></i></a>
</div>
</div>
这里我想删除子div,如果每个父节点分别有多个,但我的代码是在一个流中计算所有子div但是我需要单独计算它们,如果有多个则需要删除它们每个父div中的子div
答案 0 :(得分:2)
您需要指定仅在当前.repeatable
:
var countdiv = $(this).closest('.repeatable').children('.repeating-div').length;
上述代码表示您从触发事件的元素(.close-repeating-div
)开始,前往其.repeatable
父级,然后仅计算此div
个孩子。
答案 1 :(得分:1)
下面的javascript使用了正确的范围:
$('.repeatable').on('click', '.close-repeating-div' ,function(e){
e.preventDefault();
// `this` is the clicked <a> tag
var parent = $(this).closest('.repeatable'),
countdiv = parent.children('.repeating-div').length;
if( countdiv > 1 ){
$(this).closest('.repeating-div').remove();
}
});