首页 > 解决方案 > 当超过一个父类时如何删除输入字段?

问题描述

我正在使用有效的 jQuery 添加动态字段。我遇到了删除字段的问题。

我检查了谷歌,过去的问题 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
    });

但它不起作用。有什么帮助吗?

标签: javascriptjqueryhtml

解决方案


您需要的是最接近的,它将找到具有特定选择器的最接近的元素。

这是它的一个小例子:

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


推荐阅读