我正在使用this jquery autocomplete插件。但是,当我搜索过滤结果时,我收到此错误:
未捕获的TypeError:无法读取属性'值'未定义的
以下是检查员控制台的堆栈跟踪:
Uncaught TypeError: Cannot read property 'value' of undefined
Autocomplete.onSelect @ jquery.autocomplete.min.js:915
Autocomplete.select @ jquery.autocomplete.min.js:850
(anonymous function) @ jquery.autocomplete.min.js:195
n.event.dispatch @ jquery.min.js:3
r.handle @ jquery.min.js:3
这是我打电话的方法:
var url = $(item).data('url');
var keyField = $(item).data('keyField') !== undefined ? $(item).data('keyField') : 'id';
var valueField = $(item).data('valueField') !== undefined ? $(item).data('valueField') : 'description';
$(myItem).devbridgeAutocomplete({
serviceUrl: myUrl,
minChars: 0,
type: 'post',
deferRequestBy: 500,
transformResult: function (response) {
var json_response = $.parseJSON(response);
var suggestions = $.map(json_response.items, function (dataItem) {
var interface = $('.content-wrapper').interface();
return {value: dataItem[valueField], data: dataItem[keyField]};
});
return {suggestions: suggestions};
},
onSelect: function (suggestion) {
// Do my stuff to populate the view
}
});
查看源代码,调用函数onSelect()
时会出现问题,因为数组中没有任何建议。
为什么数组是空的?我选择了过滤后的值,因此应该有一个元素
答案 0 :(得分:1)
我找到了解决问题的方法:
这是我在GitHub上打开的issue。问题出在onSelect()
函数上。
我指的是版本 1.2.24
onSelect: function (index) { var that = this, onSelectCallback = that.options.onSelect, suggestion = that.suggestions[index]; that.currentValue = that.getValue(suggestion.value); if (that.currentValue !== that.el.val() && !that.options.preserveInput) { that.el.val(that.currentValue); } that.signalHint(null); that.suggestions = []; that.selection = suggestion; if ($.isFunction(onSelectCallback)) { onSelectCallback.call(that.element, suggestion); } },
我已将方法更改为:
onSelect: function (index) { var that = this, onSelectCallback = that.options.onSelect, suggestion = that.suggestions.length >= 1 ? that.suggestions[index] : that.suggestions; that.currentValue = that.getValue(suggestion.value); if (that.currentValue !== that.el.val() && !that.options.preserveInput) { that.el.val(that.currentValue); } that.signalHint(null); that.suggestions = []; that.selection = suggestion; if ($.isFunction(onSelectCallback)) { onSelectCallback.call(that.element, suggestion); } },
答案 1 :(得分:0)
我在访问值之前添加了检查: label = ui.item.attr("aria-label") || (item?item.value:'');