我正在使用http://jqueryui.com/demos/autocomplete/。
我正在尝试执行类似上一个fm的操作,使用自动填充功能,其中有一个标题包含其下的结果,然后是另一个,等等。http://www.last.fm
使用自定义数据示例我不确定如何正确执行此操作。有人有任何建议或指示?
<script type="text/javascript">
$(function() {
$("#findUserIdDisplay").autocomplete({
source: "ui_autocomplete_users_withuname.php",
minLength: 2,
select: function(event, ui) {
$('#findUserId').val(ui.item.id);
}.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>"+ item.label + "</a>" ) // + + "<br>" + item.desc + "</a>"
.appendTo( ul );
};
答案 0 :(得分:3)
查看JQuery Autocomplete Categories示例。在此示例中,技巧是覆盖从自动完成继承的自定义窗口小部件中的自动完成窗口小部件的_renderMenu。
http://jqueryui.com/autocomplete/#categories
示例JS小提琴 http://jsfiddle.net/ud3sh/v2Agq/4/
var data = [
{ label: "America", category: "" },
{ label: "Angola", category: "" },
{ label: "Andora", category: "" },
{ label: "Amtrak", category: "Companies" },
{ label: "Amazon", category: "Companies" },
{ label: "American Airlines", category: "Companies" },
{ label: "Amber L", category: "People" },
{ label: "Amy Quatro", category: "People" },
{ label: "Andrée González", category: "People" }
];
//widget extension
$.widget("custom.catautocomplete", $.ui.autocomplete, {
//NOTE: this will process the items in order, so a category could show up multiple times
_renderMenu: function (ul, items) {
var that = this;
var currentCategory = "";
$.each(items, function (index, item) {
if (item.category != currentCategory) {
ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
currentCategory = item.category;
}
that._renderItemData(ul, item);
});
}
});
$("#search").catautocomplete({
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(data, function (value) {
return matcher.test(value.label) || matcher.test(normalize(value.label));
}));
}
});
//utilities for accent mapping
var accentMap = {
"á": "a","ö": "o","é" : "e"
};
var normalize = function (term) {
var ret = "";
for (var i = 0; i < term.length; i++) {
ret += accentMap[term.charAt(i)] || term.charAt(i);
}
return ret;
};
答案 1 :(得分:0)
我设置了一个类似的用法,需要两个阶段......第一个是添加标题,我创建了新的菜单项,但是将值更改为“label”,然后我使用以下代码扩展了renderItem以进行自动完成:< / p>
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
var startElem = null;
if(item.value == 'label') {
startElem = $('<li></li>').addClass('categoryLabel')
.data( 'item.autocomplete', item )
.append('<a style="display:none;"></a>')
.append( item.label )
.appendTo( ul );
} else {
startElem = $('<li></li>').data( 'item.autocomplete', item )
.append( '<a>' + item.label + '</a>' )
.appendTo( ul );
}
return startElem;
};
我还将此添加到“select”事件中,以确保如果有人点击标签标题,则不会重定向
select: function( event, ui ) {
event.preventDefault();
if (ui.item.value != 'label') {
return;
}
}
我为'categoryLabel'设置CSS样式,使其样式与其他项目不同