2
使用下面的示例,我有一个tr
,我正在复制。它包含一个jQuery autocomplete
。第一次被克隆时,自动完成功能不起作用,因为附件data("items")
为空。第二次单击添加按钮时,自动完成工作。之后,再次单击添加会导致无法运行的自动完成功能。jQuery clone()复制数据...有时...?
在makeAutoComplete
函数中添加一个断点表明items
总是空的,除了单击第二次添加!
任何人都可以解释这种奇怪的行为?
HTML/JS(小提琴这里:http://jsfiddle.net/SDvF4/12/)
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Test!</title>
<style type="text/css">
tr.Template
{
display: none;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.8.18/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var textbox = $(".AutoComplete");
makeAutoComplete(textbox);
$("#addButton").click(function()
{
var attrRegex = /\d+/;
var template = $("tr.Template");
var newRow = template.clone(false);
var newRowIndex = (template.siblings().length + 1);
newRow.removeClass("Template");
newRow.find("*[id]").each(function()
{
var element = $(this);
element.attr("id", element.attr("id").replace(attrRegex, newRowIndex));
});
newRow.find("*[name]").each(function()
{
var element = $(this);
element.attr("name", element.attr("name").replace(attrRegex, newRowIndex));
});
newRow.insertBefore(template);
newRow.find(".AutoComplete").each(function()
{
makeAutoComplete($(this));
});
});
});
function makeAutoComplete(textbox)
{
var items = textbox.data("items");
var test = textbox.data("test");
if (items == null)
{
if (test == "JSM")
alert("ERROR: data.items not copied but data.test was!");
else
alert("ERROR: data.items not copied nor was data.test!");
}
textbox.autocomplete(
{
minLength: 0,
source: items
});
}
</script>
</head>
<body>
<table>
<tbody>
<tr class="Template">
<td>
<input id="test_0" name="test_0" class="AutoComplete" type="text"/>
<script type="text/javascript">
var testData = [{ label: "One", value: 1 }, { label: "Two", value: 2 }];
$("#test_0").data("items", testData);
$("#test_0").data("test", "JSM");
</script>
</td>
</tr>
</tbody>
</table>
<br/><br/>
<button id="addButton">Add</button>
</body>
</html>
您使用错误的ID。它们以'-1'开头,也变成'0',这就是模板ID。 'newRowIndex'使用'+ 1'而不是' - 1'。不过,不知道为什么'.clone()'因此暴露了不同的行为。 – pimvdb
谢谢,很好找。这解释了为什么第二个克隆工作,其他人没有工作 - 它与模板具有相同的ID,但出现在模板之前。 –
这两个数据属性都不会被复制 - 您正在使用'.clone(false)' - 来自docs它声明'布尔值指示是否应该将事件处理程序和数据与元素一起复制。“ –