【发布时间】:2013-01-14 03:07:28
【问题描述】:
我正在使用 Google Places 自动完成功能,我只是希望它在表单字段中按下回车键并且存在建议时选择结果列表中的顶部项目。我知道以前有人问过这个问题:
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
}
}
});
任何建议将不胜感激!
【问题讨论】:
-
您必须使用 google.maps.places.AutocompleteService 类并手动读取 AutocompletePrediction:developers.google.com/maps/documentation/javascript/…
-
@Mubix 在您链接到的第二个问题中接受的答案涵盖了似乎需要的内容,并添加了一些可以轻松删除的额外功能。根据这个演示,我只是从上面分叉出来的:jsfiddle.net/Ut2U4/1
-
@CraigBlagg 谢谢!我最终让它工作了。不知道为什么它第一次没有工作,但是逐行重建它得到了想要的结果!
-
太棒了。奇怪的是它没有立即工作(似乎在这里工作)。但很高兴它成功了@NChase
-
@CraigBlagg,在您的示例 (jsfiddle.net/Ut2U4/1) 中,需要确保在触发 'focusout' 时从文档中删除 'keypress' 事件(第 14 行)。否则,每次输入获得焦点时,您都会将其附加到文档中。
标签: javascript google-maps google-maps-api-3 google-places-api google-places