我一直在构建 Twitter Bootstrap Typeahead 插件的一些示例代码。
在脚本的早期开发版本中,我包含了以下内容,几乎直接从示例中提取,并进行了一些完美的自定义;
$('.building_selector').typeahead({
source: function (query, process) {
buildings = [];
map = {};
var data = [{"buildingNumber":"1","buildingDescription":"Building One"},{"buildingNumber":"2","buildingDescription":"Building Two"},{"buildingNumber":"3","buildingDescription":"Building Three"}];
$.each(data, function (i, building) {
map[building.buildingDescription] = building;
buildings.push(building.buildingDescription);
});
process(buildings);
},
updater: function (item) {
selectedBuilding = map[item].buildingNumber;
return item;
},
});
在实践中,当我将选项数组直接写入代码时,这并没有多大用处,所以我一直在研究读取写入 JSON 的外部文件。我创建了一个文件,其中仅包含数组如下;
[{"buildingNumber":"1","buildingDescription":"Building One"},
{"buildingNumber":"2","buildingDescription":"Building Two"},
{"buildingNumber":"3","buildingDescription":"Building Three"}]
我现在尝试更新 Javascript 以包含加载远程文件的代码。我可以验证文件是否存在并且位于正确的相对位置。
$('.building_selector').typeahead({
source: function (query, process) {
buildings = [];
map = {};
var data = function () {
$.ajax({
'async': false,
'global': false,
'url': "../json/buildings",
'dataType': "json",
'success': function (result) {
data = result;
}
});
return data;
}();
$.each(data, function (i, building) {
map[building.buildingDescription] = building;
buildings.push(building.buildingDescription);
});
process(buildings);
},
updater: function (item) {
selectedBuilding = map[item].buildingNumber;
return item;
},
});
在运行页面时,所有元素似乎都按预期工作,并且控制台中没有任何内容出现,直到您在文本字段内单击并正在输入。每次按键后,什么都没有发生,但控制台中会产生以下内容;
未捕获的类型错误:无法读取未定义的属性“长度”[jquery.min.js:3]
任何尝试解决此问题的想法/想法/起点将不胜感激!