我有一个时间......有时间弄清楚为什么我的带有类别和格式化结果的jQuery 自动完成功能不起作用。我已经解决了一堆关于 SO 的类似问题,并尝试了我能找到的每一个建议,但似乎没有任何效果。
虽然显示正确,但它没有将列表项附加到顶部 ul。它加一个,然后每个后续结果都附加到同一个列表项。这意味着焦点和选择方法不能按预期工作。
我试过了:
_renderItemData(ul, item)
对比_renderItem(ul, item)
- 有和没有
.data("item.autocomplete", item)
inrenderItem()
- 附加
.data("item.autocomplete", {})
到ul.append
renderMenu 方法中 - 更改类别列表项中使用的类。
任何帮助,将不胜感激。谢谢!
这是完整的代码和小提琴:
$(function () {
function format(item) {
var cell = '';
$.each(item.value, function(index, value) {
cell += "<a class='ui-autocomplete-thumbnail-link' href='" + value.url + "'>";
cell += "<img class='ui-autocomplete-thumbnail-image' src='" + value.images.small + "' />";
cell += value.presentation + "</a>";
});
return cell;
}
$.widget( "custom.categorycomplete", $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var self = this, current_category = '';
$.each(items, function(index, item) {
if (item.label !== current_category) {
current_category = item.label;
ul.append($("<li class='ui-category'>" + current_category + "</li>").data("item.autocomplete", {}));
}
self._renderItem(ul, item);
});
}
});
var jsondata = [
{
"value": [
{
"id": 1,
"name": "category1-name1",
"presentation": "category1-presentation1",
"url": "example.com/category1-url1",
"images": {
"small": "http://sipi.usc.edu/database/preview/misc/4.1.07.png"
}
},
{
"id": 2,
"name": "category1-name2",
"presentation": "category1-presentation2",
"url": "example.com/category1-url2",
"images": {
"small": "http://sipi.usc.edu/database/preview/misc/4.1.08.png"
}
}
],
"label": "category1"
},
{
"value": [
{
"id": 3,
"name": "category2-name1",
"presentation": "category2-presentation1",
"url": "example.com/category2-url1",
"images": {
"small": "http://sipi.usc.edu/database/preview/misc/4.1.01.png"
}
},
{
"id": 4,
"name": "category2-name2",
"presentation": "category2-presentation2",
"url": "example.com/category2-url2",
"images": {
"small": "http://sipi.usc.edu/database/preview/misc/4.1.03.png"
}
}
],
"label": "category2"
}
];
$('#s1').categorycomplete({
source: jsondata,
select: function (event, ui) {
window.location.href = ui.item.value[0].url.replace(window.location.host, '');
return false;
}
})
.data( "categorycomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.data("item.autocomplete", item)
.append(format(item))
.appendTo(ul);
};
});