2010-04-18 45 views
12

我有一個使用jQuery自動完成與動態創建的輸入(再次使用jQuery創建)的問題。我無法自動完成綁定到新的輸入。正在創建jQuery自動完成動態創建的輸入

自動完成

 $("#description").autocomplete({ 
     source: function(request, response) { 
      $.ajax({ 
       url: "../../works_search", 
       dataType: "json", 
       type: "post", 
       data: { 
        maxRows: 15, 
        term: request.term 
       }, 
       success: function(data) { 
        response($.map(data.works, function(item) { 
         return { 
           label: item.description, 
           value: item.description 
         } 
        })) 
       } 
      }) 
     }, 
     minLength: 2, 
    }); 


新表

var i = 1; 
var $table = $("#works"); 
var $tableBody = $("tbody",$table); 

$('a#add').click(function() { 
    var newtr = $('<tr class="jobs"><td><input type="text" name="item[' + i + '][quantity]" /></td><td><input type="text" id="description" name="item[' + i + '][works_description]" /></td></tr>'); 
    $tableBody.append(newtr); 
    i++; 
}); 

我知道,這個問題是由於內容輸入行的頁已經被加載後但我無法弄清楚如何避開它。我已經閱讀了幾個相關的問題,並且遇到了jQuery live方法,但我仍然陷入困境!

有什麼建議嗎?

回答

24

首先,您要存儲選項.autocomplete(),如:

var autocomp_opt={ 
     source: function(request, response) { 
      $.ajax({ 
       url: "../../works_search", 
       dataType: "json", 
       type: "post", 
       data: { 
        maxRows: 15, 
        term: request.term 
       }, 
       success: function(data) { 
        response($.map(data.works, function(item) { 
         return { 
           label: item.description, 
           value: item.description 
         } 
        })) 
       } 
      }) 
     }, 
     minLength: 2, 
    }; 

它更整潔使用class屬性用於標記input,如:

<input type="text" class="description" name="item[' + i + '][works_description]" /> 

最後,當你創建一個新的表格行申請.autocomplete()與已存儲的選項autocomp_opt

$('a#add').click(function() { 
    var newtr = $('<tr class="jobs"><td><input type="text" name="item[' + i + '][quantity]" /></td><td><input type="text" class="description" name="item[' + i + '][works_description]" /></td></tr>'); 
    $('.description', newtr).autocomplete(autocomp_opt); 
    $tableBody.append(newtr); 
    i++; 
}); 
+1

它的工作原理就像一個魅力,謝謝! – Jamatu 2010-04-18 20:00:50

0

我發現我需要把德自動完成追加打完:

$tableBody.append(newtr); 
$('.description', newtr).autocomplete(autocomp_opt);