2013-10-22 98 views
0

我一直對這個和它的駕駛我瘋狂d:綁定功能動態jQuery的

所以,我有這樣的代碼:

<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」失去焦點,它會在我的桌子上添加一條新線。 這項工作與我的網頁上定義的第一個輸入,但它並沒有在新的...

謝謝!

以防萬一,一點點fiddle

回答

2

這裏就是你們的榜樣工作: http://jsfiddle.net/GR5sJ/

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

爲了處理這種動態產生的場這是很好的使用jQuery的「上」欲瞭解更多文件: http://api.jquery.com/on/

Mucha suerte!

+0

聖弗萊克...只是錯過了一個參數...好吧然後..林松瞭解;)+1感謝您的鏈接。 更多信息:) Gracias Totales –

3

如果由「換新」你的意思是動態生成的輸入,那麼它的,因爲你需要事件委派:

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

卡特是對的,但我想我會添加一些信息,爲什麼。 您將blur事件處理程序附加到類.txt_posologia。它只在頁面加載時運行一次,所以額外的類不會綁定到該事件。所以你必須在文檔級別附加監聽器,所以當文檔改變時可以綁定到事件。 – Duane

+1

最好我將事件處理程序附加到最近的父文件夾中,該文件將在文檔加載時可用,但附加到文檔應始終安全。那麼說,杜安 – carter