【发布时间】:2016-03-05 12:27:02
【问题描述】:
我正在使用这个 typeahead 库:http://twitter.github.io/typeahead.js/
我设法创建了一个与他们在页面上相同的具有本地值的示例。
$( document ).ready(function() {
var globalResults = ["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Dakota","North Carolina","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"];
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
$('#search-input').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'globalResults',
source: substringMatcher(globalResults)
});
});
问题是当我更新 globalResults 时,预输入仍然显示相同的旧结果 Alambama, Alaska...
我正在尝试以这种方式更新它们,但它不起作用:
globalResults = results;
var autocomplete = $('#search-input').data('typeahead');
autocomplete.source = globalResults;
结果以字符串数组的形式从服务器检索。我调试了它,它包含了新数据,它确实将它们复制到 globalResultes 并更新了它。但不知何故,这条线什么也没做:
autocomplete.source = globalResults;
typeahead 源未更新的问题可能在哪里?
我的 html 看起来像这样:
<span style="position: relative; display: inline-block;" class="twitter-typeahead">
<input type="text" spellcheck="true" class="form-control typeahead tt-input" placeholder="Search for science, search for data ..." id="search-input" autocomplete="off"></input>
</span>
【问题讨论】:
-
如果您只更新 globalResults 变量并删除其余的更改/更新尝试会发生什么?
-
globalResults 有新值,但预先输入显示旧值。
标签: javascript autocomplete typeahead.js twitter-typeahead