如何清除绑定到Google商家信息自动填充function的输入?

以下是我的问题:我正在使用Google地方信息自动填充function从用户那里收集有关地点的信息。

在事件“place_changed”上,我保存了这些信息。 但是我希望为用户提供添加多个位置的可能性。 所以在这个地方保存之后我想清除输入。

但是,Google自动填充会自动替换输入字段中的最后一个条目。 无论如何摆脱那个?

细节 :

var inputDiv = $('#myinput'); var options = { types: ['(cities)'] }; var autocomplete = new google.maps.places.Autocomplete(inputDiv[0], options); google.maps.event.addListener(autocomplete, 'place_changed', function() { var places = autocomplete.getPlace(); savePlaces(places); console.log(inputDiv.val()); // 'Paris, France' inputDiv.val(''); console.log(inputDiv.val()); // (an empty string) setTimeout(function() { console.log(inputDiv.val()); // 'Paris, France' (It's back!) inputDiv.val(''); console.log(inputDiv.val()); // (an empty string) }, 1); setTimeout(function() { console.log(inputDiv.val()); // (an empty string) }, 10); } 

你会告诉我,看起来很好,只需在暂停时清除它。 但是当我点击输入时(它失去了焦点)。 最后一个条目又回来了!

有什么想法解决这个问题? 我没有在Google文档中找到诸如此类的function

 autocomplete.clear(); 

谢谢!

看来自动完成内部监听输入的模糊事件,所以让我们给它一些东西来监听并在之后清除字段:

 inputId_div.blur(); setTimeout(function(){ inputId_div.val('') inputId_div.focus();},10); 

上一个术语仍存在于自动完成对象中。

解决方案:清除输入框,然后创建一个新的自动完成对象。 还要确保删除以前的事件侦听器。

宣言:

 var input = document.getElementById('autocomplete'); var autocomplete; var autocompleteListener; var onPlaceChange = function() {...}; var initAutocomplete = function() { autocomplete = new google.maps.places.Autocomplete(input); autocompleteListener = google.maps.event.addListener(autocomplete, 'place_changed', onPlaceChange); }; 

清除:

 input.value = ""; google.maps.event.removeListener(autocompleteListener); initAutocomplete(); 

以前的自动完成对象应该是垃圾回收。 如果我错了,请纠正我。 为确保暴露内存泄漏,您可以手动删除它。

清除你可以使用的地方:

 autocomplete.set('place',null); 

它也触发了place_change事件。

不确定这个问题是否仍然存在,但我找到了一个适合我的修复程序

 google.maps.event.addListener(autoComplete, 'place_changed', function() { $this.one("blur",function(){ $this.val(""); }); //[DO YOUR CODE HERE] setTimeout(function(){ $this.val(""); },10); }); 

$ this是对自动填充字段的jQ引用。 当您键入值并选项卡进入自动完成列表并按Enter键时,将触发模糊事件。 当您使用鼠标单击某处时,模糊事件将触发并清除该字段。

如果在键入后直接使用鼠标来选择结果,则不会触发模糊。 然后超时将从您的字段中删除值。

在输入后清除场地似乎是一个荒谬的黑客,但我花了4个小时在网上搜索,看看谷歌的API并没有找到更好的解决方案。

作为Dr.Molle优秀答案的略微增强,您可以使用z-index属性来解决闪存问题,至少在最近的浏览器中是这样:

 var input = $('#[id of autocomplete field]'); $(input).blur(); setTimeout(function() { var container = $('.pac-container'); var zIndex = $(container).css('z-index'); $(container).css('z-index', -1); input.val('') input.focus(); setTimeout(function() { $(container).css('z-index', zIndex); }, 200); }, 10); 

为了更好的互联网……

只需触发模糊,即可调用Google商家信息来开展业务。 然后,执行你的逻辑。

 inputId_div.trigger('blur'); 

如果Google值的闪烁存在问题,请尝试将下一个操作链接起来。

尝试:

 document.getElementById('myinput').value = ''; 

要么

 inputId_div.value = ''; 

我不确定你为什么使用inputId_div[0] 。 我想它一定是jQuery的东西。