我一直在努力让 jQuery UI Autocomplete 输出自定义 HTML。这是我的代码。
$(document).ready(function(){
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var self = this,
currentCategory = "";
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "<ul class='autocomplete-category'></ul></li>" );
currentCategory = item.category;
}
self._renderItem( ul, item);
});
}
});
var data = [
{ label: "anders", category: "Antigen" },
{ label: "andreas", category: "Antigen" },
{ label: "antal", category: "Antigen" },
{ label: "annhhx10", category: "Products" },
{ label: "annk K12", category: "Products" },
{ label: "annttop C13", category: "Products" },
{ label: "anders andersson", category: "People" },
{ label: "andreas andersson", category: "People" },
{ label: "andreas johnson", category: "People" }
];
$( "#typeAhead" ).catcomplete({
delay: 0,
source: data,
})
.data( "catcomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.catcomplete", item )
.append( $( "<a class='ui-menu-item'></a>" ).text( item.label ) )
.appendTo( $('ul').last('.autocomplete-category'));
};
});
通过将列表嵌套在 renderItem 函数中,我似乎遇到了麻烦。HTML 输出正是我想要的。但是,当我“keydown”时,我得到一个 javascript 错误(项目未定义)。
有什么想法或建议吗?我几乎什么都试过了。