jquery在动态添加的行上自动完成

时间:2010-08-27 16:18:16

标签: jquery jquery-ui jquery-autocomplete

我正在为我的网络应用程序使用jQuery UI自动完成插件 它对我现有的行完全正常,但对我动态添加的行不起作用。

这是我的jquery代码。

$(function ()
{
    var tab = $("#tabs-6");
tab.find("input[name='newContactName']").autocomplete(
{
        source: function(request, response) {
            var cachedRequest = $(this).data("cachedRequest");
            // Previous data is cached, so new data is a subset of this
            if (cachedRequest != null && 
                    cachedRequest.length > 0 && 
                    request.term.indexOf(cachedRequest) >= 0)
            {
                ..some code..
            }
            else
            {
                var input = $(this);
                $.ajax({
                    ..some code..
                    success: function(data) 
                    {..some code..
                    }

                }); 

            }
        },
        minLength: 3,
        delay: 500
    }
);

tab.find("input[name='newContactName']").bind('autocompleteselect', function(event, ui) {
    $(this).prev("input[name='newContactId']").val(ui.item.person_id);
    }); 

/* Customizing the autocomplete suggestions box that pops up.
*/
var input1=$("input[name='newContactName']"); 
input1.each(function (){
$(this).autocomplete("widget").css("height", "10em");
$(this).autocomplete("widget").css("overflow", "auto"); 
$(this).autocomplete("widget").css("width", "210px");
});

});

这是现有行的自动完成插件的jQuery代码,对于新添加的行,这是我要插入的html

var html = '<tr>..first 8 td elements.. <td><input type="text" name="newContactName"> </td>'+
        ..some more td elements</tr>';

var newRow = $(html).insertAfter(row); // insert content,where row is my current row
newRow.find("td:nth-child(9) input[name='newContact']").autocomplete();

我如何确保自动完成功能也适用于我新添加的行?

1 个答案:

答案 0 :(得分:1)

我看到一些可能错误的事情。

首先,当您添加新行时,将输入的名称设置为“newContactName”,但是当您找到()时,您会查找“name ='newContact'”。

此外,在find()的结果上调用autocomplete()时,您需要指定source选项。由于您将源设置为非动态行中的函数,因此您可能希望将其分解为命名函数,并在自动完成()调用中使用命名函数作为源。

希望这会有所帮助......