在AJAX内容上运行Google自动完成功能

时间:2018-04-11 23:45:36

标签: javascript ajax autocomplete

我的网站通过AJAX加载所有内容,其中包括我正在使用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());
    });
  }
}
&#13;
<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

initAutocomplete函数是Google Maps脚本网址中指定的回调(作为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。