我正在尝试在同一页面中集成多个 Google Places 自动完成字段,但我无法弄清楚为什么这个虚拟代码有效:
$ ->
options = types: ["(cities)"]
insts = []
elements = document.getElementsByClassName('autocomplete_city')
insts[0] = new google.maps.places.Autocomplete(elements[0], options)
google.maps.event.addListener insts[0], "place_changed", ->
place = this.getPlace()
datas = place.geometry.location.lat()+"::"+place.geometry.location.lng()
$(elements[0]).next('input.autocomplete_city_id').val(datas)
insts[1] = new google.maps.places.Autocomplete(elements[1], options)
google.maps.event.addListener insts[1], "place_changed", ->
place = this.getPlace()
datas = place.geometry.location.lat()+"::"+place.geometry.location.lng()
$(elements[1]).next('input.autocomplete_city_id').val(datas)
虽然这个循环版本不起作用:
$ ->
options = types: ["(cities)"]
insts = []
elements = document.getElementsByClassName('autocomplete_city')
i = 0
for element in elements
insts[i] = new google.maps.places.Autocomplete(element, options)
google.maps.event.addListener insts[i], "place_changed", ->
place = this.getPlace()
datas = place.geometry.location.lat()+"::"+place.geometry.location.lng()
$(element).next('input.autocomplete_city_id').val(datas)
i += 1
在这种情况下,只有最后一个“autocomplete_city_id”被自动完成数据填充,即使您输入第一个自动完成输入(=接收者的“元素”变量始终是数组中的最后一个)
这两个片段不是完全相同还是我错过了一些严肃的 Javascript OOP 原则?这是一个 Coffeescript 陷阱吗?