我在 http://jqueryui.com/demos/autocomplete/ 使用了“自定义数据和显示”示例并对其进行了一些简化,这样我就可以拥有值和 ID,如下所示:
$(function() {
var prd = [
{ s: "hallo", v: "1" },
{ s: "hey", v: "2" },
{ s: "alloh", v: "3" }
];
$("#product").autocomplete({
source: prd,
minLength: 0,
focus: function(event, ui) {
$("#product").val(ui.item.s);
return false;
},
select: function(event, ui) {
$("#product").val(ui.item.s);
$("#productId").val(ui.item.v);
return false;
}
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.s + "</a>")
.appendTo(ul);
};
});
问题是,如果没有 minLength:0,它永远不会弹出,而如果使用 minLength:0,它只会弹出一个空文本框(键入一个字符,然后将其删除)。
最佳答案
Jqueryui 自动完成对“标签”和“值”的使用几乎是自动的。将您的 's' 和 'v' 更改回 'label' 和 'value',一切都会按预期工作:
<script>
$(function() {
var prd = [
{ label: "hallo", value: "1" },
{ label: "hey", value: "2" },
{ label: "alloh", value: "3" }
];
$("#product").autocomplete({
source: prd,
minLength: 0,
focus: function(event, ui) {
$("#product").val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#product").val(ui.item.label);
$("#productId").val(ui.item.value);
return false;
}
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
});
</script>
关于jQuery UI 自动完成仅弹出 minLength : 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10565321/