我正在使用 jQuery 添加动态字段,该字段有效。我遇到了有关删除字段的问题。
我在 google 上查了一下,StackOverflow 上过去的问题,每个人都在使用
$('.optionBox').on('click','.remove_button',function() {
$(this).parent().remove();
});
或
$('.optionBox').on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
为什么使用上面的代码,因为它们只有一个父类。
$('.optionBox').append('<div class="block"><input type="text" /><span class="remove">Remove Option</span></div>');
现在我的问题是,我有超过 1 个父类,例如
$('.optionBox').append('<div class="clearfix"></div>
<div class="custom_fields">
<div class="col-md-3">
<div class="form_group">
<input type="text" name="" class="form_control">
</div>
</div>
<div class="col-md-3">
<div class="form_group">
<input type="text" name="" class="form_control">
</div>
</div>
<div class="col-md-3">
<div class="row">
<div class="col-md-6">
<div class="form_group">
<div class="p_a_div">
<input type="text" class="form_control" />
</div>
</div>
</div>
<div class="col-md-6">
<div class="form_group">
<div class="btn_row remove_field">
<span> - </span> Remove </div>
</div>
</div>
</div>
</div>
</div>
</div>');
我尝试删除该字段,因此我使用了
$('.optionBox').on('click', '.remove_field', function(e){
e.preventDefault();
$(this).parent('.custom_fields').remove(); //Remove field html
x--; //Decrement field counter
});
但它不起作用。有什么帮助吗?
最佳答案
您需要的是closest这将找到具有特定选择器的最近元素。
这是一个小例子:
$('.optionBox').append('<div class="clearfix"></div> <div class="custom_fields"> <div class="col-md-3"> <div class="form_group"> <input type="text" name="" class="form_control"> </div> </div> <div class="col-md-3"> <div class="form_group"> <input type="text" name="" class="form_control"> </div> </div> <div class="col-md-3"> <div class="row"> <div class="col-md-6"> <div class="form_group"> <div class="p_a_div"> <input type="text" class="form_control" /> </div> </div> </div> <div class="col-md-6"> <div class="form_group"> <div class="btn_row remove_field"> <span> - </span> Remove </div> </div> </div> </div> </div> </div> </div>');
$('.optionBox').on('click', '.remove_field', function(e){
e.preventDefault();
$(this).closest('.custom_fields').remove(); //Remove field html
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="optionBox"></div>
关于javascript - 当多个父类时如何删除输入字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51586419/