我正在使用 Google Places Autocomplete,我只是希望它在表单字段中按下回车键并且存在建议时选择结果列表中的顶部项目。我知道之前有人问过这个问题:
Google maps Places API V3 autocomplete - select first option on enter
Google maps Places API V3 autocomplete - select first option on enter (and have it stay that way)
但这些问题的答案似乎并没有真正起作用,或者它们解决了特定的附加功能。
看起来像下面这样的东西应该起作用(但它不起作用):
$("input#autocomplete").keydown(function(e) {
if (e.which == 13) {
//if there are suggestions...
if ($(".pac-container .pac-item").length) {
//click on the first item in the list or simulate a down arrow key event
//it does get this far, but I can't find a way to actually select the item
$(".pac-container .pac-item:first").click();
} else {
//there are no suggestions
}
}
});
如有任何建议,我们将不胜感激!
在发现最佳答案是 this one 之前,我已经阅读了这个问题的许多答案以及链接问题的答案很多次。 (注意:遗憾的是,这不是公认的答案!)。
我已经修改了 2 或 3 行,将它变成一个您可以在代码中复制/粘贴的现成函数,并应用于许多输入
如果需要的话。在这里:
var selectFirstOnEnter = function(input) { // store the original event binding function
var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent;
function addEventListenerWrapper(type, listener) { // Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected, and then trigger the original listener.
if (type == "keydown") {
var orig_listener = listener;
listener = function(event) {
var suggestion_selected = $(".pac-item-selected").length > 0;
if (event.which == 13 && !suggestion_selected) {
var simulated_downarrow = $.Event("keydown", {keyCode: 40, which: 40});
orig_listener.apply(input, [simulated_downarrow]);
}
orig_listener.apply(input, [event]);
};
}
_addEventListener.apply(input, [type, listener]); // add the modified listener
}
if (input.addEventListener) {
input.addEventListener = addEventListenerWrapper;
} else if (input.attachEvent) {
input.attachEvent = addEventListenerWrapper;
}
}
用法:
selectFirstOnEnter(input1);
selectFirstOnEnter(input2);
...