0
我有一個由輸入行組成的表。只要在每行的第一個輸入中選擇自動完成值,就會動態地克隆和添加行。JQuery自動完成生成的輸入與「回收」ID
每次添加新行時,我想將.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);
};
}