在jQuery上动态绑定函数

bind function dynamically on jQuery

本文关键字:函数 动态绑定 jQuery      更新时间:2023-09-26

我一直在研究这个问题,这让我发疯 D:

所以,我有这个代码:

<table class="table table-condensed table-bordered table-hover" id="tbl_indicaciones">
<thead><tr>
<th>INDICACIÓN FARMACOLÓGICA</th><th>POSOLOGÍA</th><th>REALIZADO</th>
</tr></thead>
<tbody>
<tr>
<td><input type="text"></td>
<td><input type="text" class="txt_posologia"></td>
<td></td>
</tr>
</tbody>
</table>

和:

$(".txt_posologia").blur(function(){
    guardarIndicacion($(this));
});
var guardarIndicacion = function(elemento){
    //REVISAR QUE LOS CAMPOS TENGAN VALORES
    var indicacion = $(elemento).parent().parent().find('td:eq(0)').find('input:eq(0)');
    if(indicacion.val() == "" || $(elemento).val() == ""){
        alert("Debe ingresar ambos campos");
        indicacion.focus();
    }else{
        //REVISO SI SOY EDITABLE
        if($(elemento).attr("data-editable") != "false"){
            //HAGO ALGO
            //AGREGO LINEA A TABLA
            try{$("#tbl_indicaciones").find('tbody').
                append($('<tr>').
                    append($('<td>').html("<input type='"text'">")).
                    append($('<td>').html("<input type='"text'" class='"txt_posologia'">").on('blur', function() {guardarIndicacion($(this))}))
                );}catch(e){alert(e.toString)}
            //ME HAGO NO EDITABLE
            $(elemento).attr("data-editable", "false");
        }
    }
}

因此,每当我的"输入.txt_posologia"失去焦点时,它都会在我的表格上添加一个新行。这适用于我的页面上定义的第一个输入,但它不适用于新输入......

谢谢!

以防万一,有点小提琴

如果"新输入"是指动态生成的输入,那么这是因为您需要事件委派:

$(document).on('blur', '.txt_posologia', function(){
    guardarIndicacion($(this));
});

这是您的工作示例:http://jsfiddle.net/GR5sJ/

$( document ).on( "blur", ".txt_posologia", function() {
  guardarIndicacion($(this));
});

为了处理这种动态生成的字段,最好使用 jquery 'on' 有关此处的更多文档:http://api.jquery.com/on/

慕夏苏尔特!