我正在尝试将多个 Google 地方信息自动完成字段集成到同一页面中,但我就是不明白为什么这个虚拟代码会起作用:
$ ->
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”被填充为自动完成数据(=接收器的“element”变量始终是数组中的最后一个)
这两个片段不是完全相同还是我错过了一些重要的 Javascript OOP 原则?这是一个 Coffeescript 陷阱吗?
最佳答案
正如 CoffeeScript 网站上提到的:
When using a JavaScript loop to generate functions, it's common to insert a closure wrapper in order to ensure that loop variables are closed over, and all the generated functions don't just share the final values. CoffeeScript provides the do keyword, which immediately invokes a passed function, forwarding any arguments.
您可能可以将代码修改为:
$ ->
options = types: ["(cities)"]
insts = []
elements = document.getElementsByClassName('autocomplete_city')
i = 0
for element in elements
do (element) ->
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
其他:for
语句可以像 for element, index
一样使用。然后您可以删除 i = 0
及其增量。
关于javascript - Coffeescript 循环谷歌位置自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19114804/