我正在使用Google Places Autcomplete API和jQuery。它的基本功能正常。我想要做的是,如果有人在自动填充中键入了与我希望选择该项目以及要触发的place_changed
事件的选项之一完全相同的内容。这是因为我在需要触发的地方改变了监听器中的一些逻辑。我们的想法是,如果有人输入与自动填充选项之一完全相同的文本,那么它应该像有人点击该选项一样。
这就是我尝试过的,其中userLocation是输入:
$("#userLocation").keyup(function(e){
//if the text is at least 4 chars long
if($("#userLocation").val().length > 4)
{
//iterate through each of the autocomplete options
$(".pac-item").each(function(){
if($(this).text() == $("#userLocation").val() )
{
//does not do what I need it to
$(this).trigger("place_changed");
}
});
}
});
我也尝试用trigger("place_changed")
替换.trigger("click")
,但无济于事。
有没有人这样做过?任何人都可以建议另一种方法来尝试使这项工作?非常感谢任何建议,谢谢!
答案 0 :(得分:5)
如答案here中所述:
您必须调用google.maps.event.trigger
函数才能进行如下调用。
$("#userLocation").keyup(function(e){
//if the text is at least 4 chars long
if($("#userLocation").val().length > 4)
{
//iterate through each of the autocomplete options
$(".pac-item").each(function(){
if($(this).text() == $("#userLocation").val() )
{
google.maps.event.trigger(autocomplete, 'place_changed');
}
});
}
});
documentation显示您还可以将参数传递给trigger
函数,该函数将传递给'place_changed'事件的事件侦听器。
答案 1 :(得分:0)
你也可以尝试使用自动完成输入键事件并使用javascript触发。
请尝试以下代码。
//For Set Location pin point
var searchtext = "New York, NY";
var input = document.getElementById('pac-input');
$('#pac-input').val(searchtext);
setTimeout(function () {
google.maps.event.trigger(input, 'focus');
google.maps.event.trigger(input, 'keydown', { keyCode: 13 });
}, 10);
//End