Google通过类名将自动填充功能无法正常工作

时间:2014-03-05 11:58:56

标签: jquery google-maps google-maps-api-3 autocomplete

嗨我有一个文本框并且在焦点上它自动完成的地方,街道,如果我选择id,这个名字对我有用,但后来我有很多动态文本框控件,所以我有固定的类名,相同的代码如果我按classname

选择,则无法正常工作

JS FIDDLE DEMO

代码:

 getPlace();
 getPlace_dynamic();

     function getPlace() {
         var defaultBounds = new google.maps.LatLngBounds(
         new google.maps.LatLng(-33.8902, 151.1759),
         new google.maps.LatLng(-33.8474, 151.2631));
         var input = document.getElementById('Destination');
         // var input = document.getElementsByClassName('destination');
         var options = {
             bounds: defaultBounds,
             types: ['establishment']
         };
         autocomplete = new google.maps.places.Autocomplete(input, options);
     }

     function getPlace_dynamic() {
         var defaultBounds = new google.maps.LatLngBounds(
         new google.maps.LatLng(-33.8902, 151.1759),
         new google.maps.LatLng(-33.8474, 151.2631));

         var input = document.getElementsByClassName('myClass');
         var options = {
             bounds: defaultBounds,
             types: ['establishment']
         };
         autocomplete = new google.maps.places.Autocomplete(input, options);
     }

<input id="Destination" tabindex="1" class="txt_box" type="text" />
</br>
</br>Later Dynamically generated
<input tabindex="1" class="myClass" type="text" />
<input tabindex="1" class="myClass" type="text" />

1 个答案:

答案 0 :(得分:10)

document.getElementsByClassName('myClass')

返回具有该className(myClass)的元素数组。

所以你需要做的是迭代每个元素并将其分配给Google自动完成api,如下所示

for (i = 0; i < input.length; i++) {
        autocomplete = new google.maps.places.Autocomplete(input[i], options);
}

JSFiddle