当我尝试实现自动完成使用下面的代码,我得到一个错误说:
.data("autocomplete") is undefined
如果我从最后删除.data()方法,它工作正常(只是与出的可定制的图形.data()提供)。任何人都可以告诉我发生了什么问题?
$("input#testInput").bind("autocompleteselect",function (event,ui) {
}).autocomplete({
appendTo: "#autoCompList",source: function (request,response) {
$.ajax({
url: JSONP CALL URL
dataType: "jsonp",data: {
featureClass: "P",style: "full",maxRows: 12,name_startsWith: request.term
},success: function (data) {
response($.map(data.data,function (item) {
fbPageJson = item;
return {
label: item.name,image: item.picture,json: item,}
}));
},});
}
}).data("autocomplete")._renderItem = function (ul,item) {
return $("<li></li>").data("item.autocomplete",item).append("<a><img src='" + item.image + "' alt='no photo'/></a>" + item.label).appendTo(ul);
};
解决方法
我有同样的问题,并基于1.10.0版本的jquery ui,我想你应该试试
data('uiAutocomplete')
代替
data('autocomplete')
基于Johnny的评论,我检查了.data()函数的工作原理。是的,当选择器没有找到任何项目时,jQuery从.data()调用返回null。
因此,如果您的选择器没有匹配元素,则不会创建自动完成对象,并将其添加到自定义数据对象。
所以它似乎是更好地这样做:
$(selector).autocomplete({ your autocomplete config props here });
if ( $(selector).data() ) {
// some jQueryUI versions may use different keys for the object. so to make sure,// put a breakpoint on the following line and add a watch for $(selector).data().
// then you can find out what key is used by your jQueryUI script.
var ac = $(selector).data('uiAutocomplete');
if ( ac ) {
// do what you want with the autoComplete object. below is the changed version of an example from jqueryUI autocomplete tutorial
ac._renderItem = function(ul,item) {
return $("<li>")
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
}
}