在addListener中传递google事件数据

时间:2016-04-03 12:44:49

标签: javascript jquery google-maps-api-3 google-places-api

我有一个可变数量的文本字段,我正在动态地初始化Google地图自动填充。

问题在于每次触发 place_changed 事件时,我都需要确切地知道它被触发了哪个输入框。如何将此数据传递到 saveLocation 功能?

目前,事件评估为未定义。

  initAutocomplete = function (element) {
        autocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */(element), {});

        autocomplete.addListener('place_changed', saveLocation);
    },

    saveLocation = function (event) {
        console.log(event);
        var place = autocomplete.getPlace();
    },

1 个答案:

答案 0 :(得分:4)

可能的方法:

var initAutocomplete = function (element) {
  var autocomplete = new google.maps.places.Autocomplete(element);
  google.maps.event.addListener(autocomplete,
                                'place_changed', 
                                function(){saveLocation.call(autocomplete,element)});
},

saveLocation = function (element) {
        document.getElementsByTagName('code')[0]
          .innerHTML=element.getAttribute('name');
        var place = this.getPlace();
        
};

google.maps.event.addDomListener(window, 'load', function(){
  var inputs=document.querySelectorAll('.pac');
  for(var i=0;i<inputs.length;++i){
    initAutocomplete(inputs.item(i));
  }
});
<code></code><br/>
<input class="pac"  name="field1">field1<br/>
<input class="pac"  name="field2">field2<br/>
<input class="pac"  name="field3">field3<br/>

<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>