无法删除谷歌地方自动完成?

the*_*cat 11 javascript google-maps google-places-api

var autocomplete = new google.maps.places.Autocomplete(input, {
  types:  ['geocode']
});
Run Code Online (Sandbox Code Playgroud)

我该如何删除它?

有"autocomplete.unbindAll()"函数,但它不会删除下拉框的HTML.我有一个页面,它做了很多ajaxy的东西,因为这个下拉框继续添加,即使在页面上的给定时间只有一个自动完成:

小智 18

假设这是事情的初始化

var autocomplete = new google.maps.places.Autocomplete(input, {types: ['geocode']});
var autocompleteLsr = google.maps.event.addListener(autocomplete, 'place_changed', function() { ... });
Run Code Online (Sandbox Code Playgroud)

谷歌地图API还提供removeListener和clearInstanceListeners以便删除. https://developers.google.com/maps/documentation/javascript/reference#event

同样作为可选步骤,您也应该删除此$(".pac-container")

google.maps.event.removeListener(autocompleteLsr);
google.maps.event.clearInstanceListeners(autocomplete);
$(".pac-container").remove();
Run Code Online (Sandbox Code Playgroud)

  • 但是,当您在一页上有多个自动完成功能时,这并没有帮助,因为当您只想删除其中一个时,所有“pac-container”都将被删除。 (5认同)

smh*_*kmr 10

即使这是一个旧帖子,我也想现在回答它,因为它会帮助某人。

在自动完成实例上删除侦听器或 unbindall() 不会删除自动建议的发生,并且从 DOM 中删除“.pac-container”不是干净的解决方案。

自动完成的新实例意味着输入元素与自动完成实例挂钩,因此我们必须清除输入元素的侦听器,而不是自动完成实例。

google.maps.event.clearInstanceListeners(input);