我正在使用带有组合框的jquery自动完成功能。我想显示一个空选项,但是每当我将我的初始选择的值设置为空字符串时,它不会显示在组合框中。
该项目存在,但它没有高度。
是否可能在自动完成组合框上有一个空选项?
该项目存在,但它没有高度。
是否可能在自动完成组合框上有一个空选项?
我曾经遇到过同样的问题,我是这样解决的:
$autocomplete.data("autocomplete")._renderItem = function(ul, item) {
return $j( "<li></li>" )
.data( "item.autocomplete", item )
.append(item.label === '' ? '<a> </a>' : "<a>" + item.label + "</a>" )
.appendTo(ul);
}
item.label === ''
) 时,我会添加一个包含非打断空格 (
) 的链接,而不是标签。"<a>" + _.escape(item.label) + "</a>"
或者使用以下代码:
$('<a/>').text(item.label)
ui-autocomplete
来处理数据项。 - scott.korinresponse(select.children("option").map(function () {
var text = $(this).text();
if (/*this.value && */(!request.term || matcher.test(text)))
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"),
value: text,
option: this
};
}));
/*this.value && */
然后我在我的样式表中添加了一个自动完成项目的规则。
.ui-autocomplete .ui-menu-item a
{
min-height: 15px;
}
所以我们找到了解决方案。您需要使用_renderItem
方法进行工作。
input.data("autocomplete")._renderItem = function(ul, item) {
var listItem;
if (item.label == "<strong></strong>") {
listItem = $("<li></li>")
.data("item.autocomplete", item)
.append("<a><br></a>")
.appendTo(ul);
} else {
listItem = $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
}
return listItem;
};
$("#ctrl").autocomplete({
source: [ "\u00A0", "One", "Two" ]
});
最近我遇到了这个问题,虽然其他解决方案大多是正确的,但我发现还缺少一步。
if (this.value && (!request.term || matcher.test(text)))
需要更改为
if (!request.term || matcher.test(text))
input.data('autocomplete')._renderItem = function(ul, item) {
return $('<li></li>')
.data('item.autocomplete', item)
.append(item.label === '<strong></strong>' ? '<a> </a>' : '<a>' + item.label + '</a>' )
.appendTo(ul);
}
这是BentOnCoding和Tim Büthe方案的混合。
$.widget( "ui.autocomplete", $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var that = this;
// add a blank item
if (this.options.blankItem) {
var blank = [{
id: "",
label: "<none>",
value: ""
}];
items = blank.concat(items);
}
$.each(items, function (index, item) {
var rendered = that._renderItemData(ul, item);
// ensure min height on blank item. hmm, maybe a class would be better...
if (index === 0 && that.options.blankItem) {
$(rendered).find('div').css('minHeight', '30px');
}
});
}
});
然后像这样使用它:
$( "#textbox" ).autocomplete({
source: contactNames,
blankItem: true
})
这里有一个Fiddle。
如果您因某种原因不想扩展小部件,您可以像这样将函数添加到change
方法中:
$( "#textbox" ).autocomplete({
create: function(){
$(this).data('ui-autocomplete')._renderMenu = function( ul, items ) {
[ _renderMenu function contents... ]
}
}
})