javascript在内部函数中保持var

时间:2016-04-21 13:23:23

标签: javascript arrays angularjs loops

我正在制作一个基于网站的仪表板。其中一项功能是显示所有客户的位置。当我将这些放在地图上时,我似乎无法正确显示弹出窗口。

function getCoordinates(locationList) {
            for (var i = 0; i < locationList.length; i++) {
                if (locationList[i].city != null) {
                    $http.get('https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/' + locationList[i].city + '.json?access_token=' + access_token)
                        .success(
                            function (data) {
                                var marker = L.marker([data.features[0].center[1], data.features[0].center[0]]).addTo(mymap);
                                marker.bindPopup(locationList[i].customerName);
                            }
                        );
                }
            }
        }

当我使用此代码时,弹出窗口将仅包含每个弹出窗口中的最后一个客户名称。有人知道如何确保使用正确用户的属性吗?

4 个答案:

答案 0 :(得分:0)

这是一个关闭问题,修复它你必须将你的$ http调用移动到这样的新函数。

function httpCall(locationList,i){
         $http.get('https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/' + locationList[i].city + '.json?access_token=' + access_token)
                        .success(
                            function (data) {
                                var marker = L.marker([data.features[0].center[1], data.features[0].center[0]]).addTo(mymap);
                                marker.bindPopup(locationList[i].customerName);
                            }
        );


}

答案 1 :(得分:0)

for循环i始终为locationList.length - 1。尝试使用本地i添加IIFE。例如,您可以使用for

替换locationList.forEach循环来解决问题

答案 2 :(得分:0)

这是一个范围问题。您的i已更新,之后,当您点击该弹出窗口时,它会读取i的最后一个值。

你应该把你的条件放在for一个函数中,该函数接受i的参数:

function getCoordinates(locationList) {
  for (var i = 0; i < locationList.length; i++) {
    conditionnalGet(i);
  }
  function conditionnalGet(i) {
    if (locationList[i].city != null) {
      $http.get('https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/' + locationList[i].city + '.json?access_token=' + access_token)
        .success(function (data) {
          var marker = L.marker([data.features[0].center[1], data.features[0].center[0]]).addTo(mymap);
          marker.bindPopup(locationList[i].customerName);
        });
    }
  }
}

答案 3 :(得分:0)

这是臭名昭着的循环问题。由于您只是定义函数而不是在for循环结束时实际执行它,因此所有函数都将具有索引i的相同值。

解决方案:是将值赋给变量并在成功回调中使用此变量。

for (var i = 0; i < locationList.length; i++) {
   if (locationList[i].city != null) {    
   var currLocation = locationList[i]; // assign the data to a variable 
   $http.get('https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/' + locationList[i].city + '.json?access_token=' + access_token)
   .success(
            function (data) {
              var marker = L.marker([data.features[0].center[1], data.features[0].center[0]]).addTo(mymap);
              marker.bindPopup(currLocation.customerName); // use the variable instead of the indexed lookup
             }
           );
   }
 }

如果有帮助,请告诉我。

相关问题