小心这个!
对于那些正在考虑手动触发 typeahead 行为(例如单击按钮)的人,我强烈建议您不要这样做。
我是为这个解决方案而来的,但我花了将近一整天的时间来解决它的问题(在我的例子中,这是一个按钮点击)。
对于那些真正想走这条黑暗道路的人,我与你分享我的丑陋代码,使其工作:
//Removes default features of typeahead
//This means that typeahead will not work like an "autocomplete", it only will be trigged when the user Click in #btnSearch button!
var txt = $("#typeahead");
//Save input events in variables (we'll need them)
eventInput = $._data(txt[0], "events").input[0];
eventBlur = $._data(txt[0], "events").blur[1];
//Remove input events
txt.unbind("blur");
txt.unbind("input");
//Set click event that triggers typeahead features manually
$("#btnSearch").click(function () {
//Clears the cache of engine for it call ajax again, without it when the term was already searched the ajax is not called!
engine.clearRemoteCache();
txt.focus(); //When we click in a button, the focus from input is lost, so we set it again to not lose the behaviors of keyboard keys (up, down, tab, etc)
txt.bind("input", eventInput); //Bind the event that we had saved
txt.trigger("input"); //Trigger input (like the answer from @epascarello)
txt.unbind("input"); //Removes it again
});
//Set event on parent of the suggestion's div, this makes the sugestion div close when user click outside it
$("body").click(function () {
if (eventBlur != undefined) {
if ($(".tt-dropdown-menu:visible").length > 0) {
eventBlur.handler(); //This event closes the suggestion menu
}
}
});
我做的另一件事是更改 typeahead.js 上的事件 "_checkInputValue" 的代码。我改变了这个:
areEquivalent = areQueriesEquivalent(inputValue, this.query);
到这里:
areEquivalent = false;//areQueriesEquivalent(inputValue, this.query);
我将它设置为 false 因为 typeahead 不要向服务器发送两个相同的请求。当用户在搜索按钮中单击两次时会发生这种情况(我的意思是,当他多次搜索他已经搜索过的相同文本时)。无论如何,如果您使用的是本地数据,则不需要这样做。