删除动态添加的字段时出错

时间:2016-10-04 03:30:04

标签: javascript jquery html twitter-bootstrap

我试图动态添加3个字段(2个文本字段和1个删除按钮)。添加按钮工作正常。问题是删除功能。它只删除删除按钮,但不删除它应该的其他2个字段。

这是我的HTML代码:

<div class="col-lg-12">

    <div class="field_wrapper form-group col-sm-12">
        <div class="form-group col-sm-4">
            <input type="text" name="id[]" value="" class="form-control"/>
        </div>
        <div class="form-group col-sm-4">
            <input type="text" name="name[]" value="" class="form-control"/>
        </div>
        <div class="form-group col-sm-4">
            <a href="javascript:void(0);" class="add_button btn btn-primary" title="Add field">Adicionar Valor</a>
        </div>
    </div>

</div>

这是javascript:

<script type="text/javascript">
$(document).ready(function(){
    var maxField = 10; //Input fields increment limitation
    var addButton = $('.add_button'); //Add button selector
    var wrapper = $('.field_wrapper'); //Input field wrapper
    //var fieldHTML = '<div><input type="text" name="field_name[]" value=""/><a href="javascript:void(0);" class="remove_button btn btn-danger2" title="Remove field">Remover</a></div>'; //New input field html 
    var fieldHTML = '<div class="field_wrapper form-group col-sm-12"><div class="form-group col-sm-4"><input type="text" name="id[]" value="" class="form-control"/></div><div class="form-group col-sm-4"><input type="text" name="name[]" value="" class="form-control"/></div><div class="form-group col-sm-4"><a href="javascript:void(0);" class="remove_button btn btn-primary" title="Add field">Remover</a></div></div>'; //New input field html 
    var x = 1; //Initial field counter is 1
    $(addButton).click(function(){ //Once add button is clicked
        if(x < maxField){ //Check maximum number of input fields
            x++; //Increment field counter
            $(wrapper).append(fieldHTML); // Add field html
        }
    });
    $(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
        e.preventDefault();
        $(this).parent('div').remove(); //Remove field html
        x--; //Decrement field counter
    });
});
</script>

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

问题是您要删除struct Sucesso { char nome_equipe[N1]; float distancia_alvo; float tempo_propulsao; }; struct Node { struct Sucesso *dados; struct Node *prox; }; typedef struct Node podio; void push(podio *p, struct Sucesso elem) { podio *novo = (struct podio*) malloc(sizeof(podio)); if(novo != NULL) { novo->dados=elem; novo->prox=*p; *p=novo; } } ,即为您提供按钮的表单组而不是预期的$(this).parent('div'),您可以使用{{1找到你添加的元素。

查看此fiddle,了解详情。

答案 1 :(得分:0)

刚改变:

set "_path=%1"

IF DEFINED _path (
    GOTO run
) ELSE (
    GOTO help
)

rem your script continues here

有:

$(this).parent('div').remove();

答案 2 :(得分:0)

使用

.closest('.field_wrapper')

Working fiddle