0

我正在尝试在同一页面中集成多个 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 陷阱吗?

4

2 回答 2

2

正如 CoffeeScript 网站上提到的:

当使用 JavaScript 循环生成函数时,通常会插入一个闭包包装器,以确保循环变量是封闭的,并且所有生成的函数不只是共享最终值。CoffeeScript 提供 do 关键字,它立即调用传递的函数,转发任何参数。

您可能可以这样修改您的代码:

$ ->
  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及其增量。

于 2013-10-01T12:56:42.157 回答
0

push我的建议是编译js中的方法可能会导致奇怪的行为。

我对您的代码进行了一些重构,并添加return到循环中。

$ ->
  options = types: ["(cities)"]

  insts = []
  elements = document.getElementsByClassName('autocomplete_city')

  for element, i in elements
    insts[i] = new google.maps.places.Autocomplete(element, options)

    google.maps.event.addListener insts[i], "place_changed", ->
      place = @.getPlace()
      datas = "#{place.geometry.location.lat()}::#{place.geometry.location.lng()}"
      $(element).next('input.autocomplete_city_id').val(datas)
      return
    return
于 2013-10-01T12:47:42.733 回答