我正在尝试创建一个 2 列自动完成功能。我理论这段代码应该是正确的,但我不断收到错误Uncaught TypeError: object is not a function
,我不知道为什么。
谁能看到我为什么会收到这个错误?这是我的小提琴- 要重现错误,请在以 . 开头的文本字段中输入至少两个字符mo
。
PS。jsFiddle 中有一个错误。如果你第一次保存后点击更新,你会得到一个 403 禁止。希望他们能尽快解决这个问题。
更新
所以我做了一些调试。从 切换jquery.min.js
到jquery.js
显示jQuery实际上在以下方面失败了each
:
TypeError: obj is undefined
length = obj.length,
所以通过这样做:
var stores = items.stores;
console.log(stores.toSource());
你会得到一个TypeError: stores is undefined
但如果你这样做:
$.each( items, function( index, item ) {
console.log(item.toSource());
});
它会输出
// Stores
({0:{id:"4058", name:"Moods"...}, 1:{id:"4059", name:"Moody"...}, label:(void 0), value:(void 0)})
// Brands
({0:{id:"4673", name:"Moods"...}, 1:{id:"4674", name:"MOOKS"...}, label:(void 0), value:(void 0)})
更新 2
似乎response(data);
删除了 JSON 对象中的命名参数。
如果你这样做:
success: function (data) {
console.log(data.stores.toSource()); // <-- This works
response(data); // But after this, it no longer works
}
现在你可以点他的:
console.log(data[0].toSource());
代码:
var data =
{"stores":[
{"id":"4058","name":"Mo-shu","city":"Oslo","fk_countryID":"NO"},
{"id":"4059","name":"Mood","city":"Oslo","fk_countryID":"NO"}
],
"brands":[
{"id":"4673","name":"Moods"},
{"id":"4674","name":"MOOKS"}
]
}
$.widget( "custom.searchAutocomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var self = this;
ul.addClass('searchAutocomplete');
ul.append('<li class="stores left"></li>');
ul.append('<li class="brands left"><li>');
$.each( items.stores, function( index, item ) {
self._renderItem( ul.find('.stores' ), item, 'store' );
});
$.each( items.brands, function( index, item ) {
self._renderItem( ul.find('.brands' ), item,'brand' );
});
},
_renderItem: function( li, item, type) {
var listItem = $('<div />');
listItem.data('ui-autocomplete-item', item );
if(type == 'store') {
listItem.append( "<a>"+ item.name + "<br /><span class='address'>Street name here</span></a>" );
} else {
listItem.append('<a>' + item.name + '</a>');
}
listItem.appendTo( li );
return listItem;
}
});
$('#search-box').searchAutocomplete({
minLength: 2,
source: data,
select: function(e, ui){
$(this).val(ui.item.name);
return false;
}
});