【问题标题】:Running Google auto-complete on AJAX content在 AJAX 内容上运行 Google 自动完成功能
【发布时间】:2018-04-12 08:14:40
【问题描述】:

我的网站通过 AJAX 加载其所有内容,其中包括我使用 Google 自动完成功能的地址表单。问题是 Google 的演示代码会在输入字段上启动侦听器,即使它还不存在,AJAX 就是这种情况。

我想不通的是如何将侦听器事件传输到实际的autocomplete 表单输入,可能是onkeyup

请原谅我在我的代码示例中使用粗略的 AJAX 替代品!

var placeSearch, autocomplete;
  
var componentForm = {
  route: 'long_name'
};
      
var options = {
  types: ['geocode'],
  componentRestrictions: {country: "us"}
};

function initAutocomplete() {
  autocomplete = new google.maps.places.Autocomplete((document.getElementById('autocomplete')),options);
  autocomplete.addListener('place_changed', fillInAddress);
}

function fillInAddress() {
  var place = autocomplete.getPlace();
  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}

function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
<div id="ajax"></div>

<a href='#' onclick='document.getElementById("ajax").innerHTML="<input class=\"form-control\" id=\"autocomplete\" placeholder=\"Enter your address...\" onFocus=\"geolocate()\" type=\"text\"><label for=\"route\"></label><input type=\"text\" id=\"route\" disabled=\"true\">";'>click me</a>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAUn3BBDhG1bXZckXyx6f2E2NSOhasl6FY&libraries=places&callback=initAutocomplete" async defer></script>

【问题讨论】:

  • 为什么不运行该代码?
  • 是的,我不知道该怎么做。
  • 这取决于你如何创建它。

标签: javascript ajax autocomplete


【解决方案1】:

initAutocomplete 函数是在 Google 地图脚本 URL 中指定的回调(作为 GET 参数)

你可以这样做

function initAutocomplete() {
  var el = document.getElementById('autocomplete');
  if(el!=null){
    autocomplete = new google.maps.places.Autocomplete(el,options);
    autocomplete.addListener('place_changed', fillInAddress);
  }
}

这意味着如果元素尚未创建,它就不会做任何事情,因此您需要在创建元素的 AJAX 调用之后调用 initAutocomplete。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 2021-06-24
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    相关资源
    最近更新 更多