您好 Knockout/typeahead 专家,我从上面的 typeahead js 得到了建议。我以数组格式提供数据
var itemsRandom= ['Apple', 'Ball','Ape'];
我的绑定(bind)代码是我在 stackoverflow 中找到的标准绑定(bind)。我将文本框绑定(bind)为
<input type="text" data-bind="typeahead:itemsRandom,value: selectedItem">
数据甚至没有绑定(bind)到 knockout js。非常感谢您的建议。
ko.bindingHandlers.typeahead = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
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) {
// console.log(str);
if (substrRegex.test(str)) {
// the typeahead jQuery plugin expects suggestions to a
// JavaScript object, refer to typeahead docs for more info
matches.push({
value: str
});
}
});
cb(matches);
};
};
var $element = $(element);
var allBindings = allBindingsAccessor();
var source = ko.utils.unwrapObservable(valueAccessor());
var items = ko.utils.unwrapObservable(allBindings.items) || 4;
var valueChange = function (item) {
allBindings.value(item);
return item;
};
debugger;
$element.attr("autocomplete", "off")
.typeahead({
hint: true,
highlight: true,
minLength: 0,
selectable: 'Typeahead-selectable'
}, {
valueKey: 'value',
source: substringMatcher(source),
items: items,
updater: valueChange
});
}
};
最佳答案
如果您使用的是最新版本的打字头,即 0.11,则代替
valueKey: 'value',
使用
displayKey: 'value',
关于javascript - Knockout Js 和 Typeahead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33766679/