How to return the id of dynamically inserted elements?

1

How to return the id of a dynamically inserted element? I do not know where I'm going wrong. When the elements are already on the page, it works normal, but all it takes is to be dynamically inserted to stop working.

if($("#_INSERIR_").length > 0)
{  
    var id_c = parseInt($("#_INSERIR_ p:last")[0].id.split("_")[1]);

    $("#novo_reg").click(function()
    {
        id_c ++;
        var html_new_reg = '<p id="reg_'+id_c+'"><a class="excluir_registro" href="#" title="Excluir este registro">Deletar</a>';
        html_new_reg += '<label>Campo_1</label> <input type="text" name="campo_1" placeholder="Insira novo registro" value="" autocomplete="off"/>';
        html_new_reg += '<label>Campo_2</label> <input type="text" name="campo_2" placeholder="Insira novo registro" value="" autocomplete="off"/></p>';

        $("#_INSERIR_").append(html_new_reg);
    });

    /* funcao para fechar */
    $("a.excluir_registro").click(function()
    {
        var del_id_c = $(this).parent().attr('id');
        console.log(del_id_c);

        //$("p#reg_"+del_id_c+"").remove();
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="_INSERIR_">  

    <p id="reg_1">
    <a class="excluir_registro" href="#" title="Excluir este registro">Deletar</a>
    <label>Campo_1</label> <input type="text" name="campo_1" placeholder="Insira novo registro" value="" autocomplete="off"/>
    <label>Campo_2</label> <input type="text" name="campo_2" placeholder="Insira novo registro" value="" autocomplete="off"/>
    </p>

    <p id="reg_2">
    <a class="excluir_registro" href="#" title="Excluir este registro">Deletar</a>
    <label>Campo_1</label> <input type="text" name="campo_1" placeholder="Insira novo registro" value="" autocomplete="off"/>
    <label>campo_2</label> <input type="text" name="campo_2" placeholder="Insira novo registro" value="" autocomplete="off"/>
    </p>
    
    <input type="submit" value="Inserir registro" class="botao_ficha" id="novo_reg"/>
</div>
    
asked by anonymous 26.08.2016 / 23:11

1 answer

1

If the element was created dynamically use on of element BODY instead of click and of course insert this id into the element that contains the clickable class ex:

$(body).on('click', '.excluir_registro', function(){

     var id = $(this).attr('id');

     // ex de teste ou sua lógica
     alert(id);
});
    
26.08.2016 / 23:24