【发布时间】:2015-11-12 11:06:25
【问题描述】:
我正在尝试使用 typeahead 渲染事件,但无法正确获取传入的参数..
参考https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#custom-events,渲染事件应该通过 4 个参数..
我已经按如下方式设置了预输入和事件处理程序:
$('#input').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'items',
source: items
})
.on('typeahead:render', onRender);
function onRender($event, $suggestions, $async, $dataSet)
{
}
按预期呈现事件文件,但未正确传递参数。
$event 是指定的 jQuery 事件对象。但是,我希望第二个参数 $suggestions 是一个包含当前建议的数组,但它只包含第一个建议。接下来的两个参数包含第二和第三个建议,而不是预期的异步标志和数据集名称。
请参阅下面的示例,了解我在做什么。发送到控制台的参数。
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);
};
};
var states = ['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 Carolina', 'North Dakota',
'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];
console.log("starting");
$('#the-basics .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: substringMatcher(states)
})
.on('typeahead:render', onRender);
function onRender($event, $suggestions, $async, $dataSet)
{
console.log($event);
console.log($suggestions);
console.log($async);
console.log($dataSet);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<div id="the-basics">
<input type="text" class="typeahead" />
</div>
【问题讨论】:
标签: javascript jquery typeahead.js typeahead