jQuery self =这会重置点击

时间:2013-02-21 16:58:28

标签: javascript jquery jquery-mobile bing-maps

我有一段代码正在jQuery Mobile框架中集成Bing地图 如果不是每个标记内显示的文本

,事情都运作良好

标记显示在正确的位置,但文本似乎更改为生成的最后一个标记

这是我的代码

for (var i = 0; i < locations.length; i++)
{
  marker_description = locations[i].description;
      marker_title = locations[i].title;
  var self = this;


  self.addMarker({'location': locations[i].lat +','+locations[i].long, 'bounds' : true })
  .click(function() {
      self.openInfoWindow({
        'title': marker_title,
        'description': marker_description
      }, this);
  });
}

所以问题是当我点击每个标记时,打开的弹出窗口显示循环的最后一项的值。

1 个答案:

答案 0 :(得分:2)

当您调用的回调被调用时,您的变量已经改变。

您可以通过立即执行的闭包来保护它们:

for (var i = 0; i < locations.length; i++) {
   (function(i){
      var marker_description = locations[i].description; // be careful to use local variables
      var marker_title = locations[i].title;
      var self = this;
      self.addMarker({'location': locations[i].lat +','+locations[i].long, 'bounds' : true })
      .click(function() {
          self.openInfoWindow({
            'title': marker_title,
            'description': marker_description
          }, this);
      });
  })(i);
}

请注意我添加的var以使变量成为本地。