我有一个由输入行组成的表。只要在每行的第一个输入中选择了自动完成值,就会动态克隆并添加行。
每次添加新行时,我都想将.autocomplete应用于第一个输入。通常这很容易,如jsfiddle所示。
我有一个不同的方法,我正在改变选择的输入ID。我认为这就是为什么我无法对克隆线应用自动完成,但我无法弄清楚为什么?
以下是相关代码(jsfiddle here)
// Make new line. (I have additional code for improved functionality in my production code)
function newLine() {
// Send the line to backend for updating mysql. Data returned is
// the mysql id for the "autocompleted" line. Emulated here by a random number
var randomNumber = Math.floor(Math.random() * 100) + 1
$("#idLine0").attr("id", "idLine" + randomNumber)
//Make clone of the last line
var row = $("#test tr:last").clone(true);
//Give the ID "idLine0" (which I've reserved for the bottom line) to the new line.
$(".AC", row).val("").attr({
"id": "idLine0",
"placeholder": "Autocomplete does not work here"
})
row.insertAfter("#test tr:last");
//$(".AC").autocomplete("destroy")
applyAutocomplete("#idLine0")
}
function applyAutocomplete(id) {
$(id).autocomplete({
source: [{
value: "ActionScript",
type: "type 1",
comment: "none"
}, {
value: "TestScript",
type: "type 2",
comment: "lots"
}, {
value: "AlphaScript",
type: "type 3",
comment: "even more"
}, {
value: "BravoScript",
type: "type 4",
comment: "lots and lots"
}, {
value: "CharlieScript",
type: "type 5",
comment: "comment"
}, {
value: "DeltaScript",
type: "type 6",
comment: "no comment"
}],
minLength: 1,
open: function (event, ui) {
var header = "<li style='border-bottom: 1px solid black; padding-top: 10px;'>" +
"<a style='font-size:1em;font-weight:bold; display:inline-block;'>" +
"<span class='ui-span'>Product</span><span class='ui-span'>Type</span>" +
"<span class='ui-span'>Comment</span></a></li>"
$("ul.ui-autocomplete[style*='block']").find("li:first").before(header);
},
select: function (event, ui) {
console.log($(this.element))
newLine()
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a><span class='ui-span'>" + item.value +
"</span><span class='ui-span'>" + item.type +
"</span><span class='ui-span' style='width:250px;'>" + item.comment + "</span></a>")
.appendTo(ul);
};
}
答案 0 :(得分:1)
稍微处理好你的问题后,我看到了这一行:
var row = $("#test tr:last").clone(true);
这一行是问题,更具体地说是“真正的”bool参数。 正如您在jquery .clone docs上看到的那样:
一个布尔值,指示是否应将事件处理程序与元素一起复制...
这基本上意味着该元素上的所有内容都将是clonned,handdlers,触发器等等......每次使用第一个输入元素时,您都可以看到自动完成工作和克隆行。
所以,改变一下:
var row = $("#test tr:last").clone(true);
对此:
var row = $("#test tr:last").clone();
我为你的jsfiddle做了一个更“干净”的版本:http://jsfiddle.net/JuanHB/8uhNq/3/