JQuery AutoComplete和Clone

我在使用jQuery clone时尝试将jQuery AutoComplete应用于表中的多行时遇到问题。 AutoComplete在第一行上工作,但在向表中添加其他行时无法工作。 到目前为止,我有以下内容:

HTML表格:

Item Description
input name="product_title" id="product_title" type="text">

克隆脚本:

 function addRow(){ $('#myTable tr:last').clone(true).insertAfter('#myTable tr:last'); $('#myTable tr:last input').val(""); $('#myTable tr:last input:first').focus(); } 

自动完成脚本:

 $().ready(function() { $("#product_title").autocomplete(products, { width: 380, matchContains: "word", formatItem: function(row) { return row.title; } }); $('#product_title').result(function(event, data) { $('#product_description').val(data.description); }); }); 

自动完成的数据来自简单的MySQL查询,该查询定义了产品标题和描述。

目前,添加新行的工作正常,表的第一行的自动完成也是如此,但是它无法处理添加的任何其他行。 即使我手动向HTML表添加第二行,AutoComplete也不会对此工作。

有没有人知道是否有一种(简单的)方法来修改上面的代码来使其工作? 对于jQuery我是新手,所以越多细节就越好。

提前致谢!!!

这是在动态添加元素上使用插件的常见问题。 它通常需要在插入DOM后调用新元素上的插件。 您可以创建一个简单的辅助函数,而不是为初始页面加载元素和新元素复制相同的代码,该函数使用父元素作为主要引用,并仅在该元素内搜索要应用插件的元素。

重要提示:克隆新行时,您正在重复ID,并且ID在页面中必须是唯一的。 以下代码将您的ID更改为类,您需要在标记中执行相同操作。

 var $table; $(function() { $table=$('#myTable'); var $existRow=$table.find('tr').eq(1); /* bind to existing elements on page load*/ bindAutoComplete($existRow); }); function addRow(){ var $row=$table.find('tr:last').clone(true); var $input=$row.find('input').val(""); $table.append($row); bindAutoComplete($row ); $input.focus(); } function bindAutoComplete($row ){ /* use row as main element to save traversing back up from input*/ $row.find(".product_title").autocomplete(products, { width: 380, matchContains: "word", formatItem: function(row) { return row.title; } }); $row.find('.product_title').result(function(event, data) { $row.find('.product_description').val(data.description); }); } 

我认为问题是,使用clone() ,您克隆一个元素,该元素已经具有自动完成属性,然后自动完成不能再“添加”到新元素。 我认为你不应该clone() ,你应该使用元素的原始HTML代码并将其放入。

编辑:

我是如何修理它的:

  1. 您要克隆的原始输入字段的autocomplete("destroy")
  2. 克隆元素并向其添加自动完成

并且不要使用clone(true) ,但你可以使用clone()

Charlietfl的post解决了我的问题,我必须做的唯一改变就是取代:

var $row=$table.find('tr:last').clone(true);

var $row=$table.find('tr:last').clone(); 删除true

希望这有助于别人:)