JavaScript 在内部函数中保留一个 var
javascript keeping a var within inner functions
我正在制作一个基于网站的仪表板。 功能之一是显示所有客户的位置。 当我将它们放在地图上时,我似乎无法正确弹出。
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);
}
);
}
}
}
当我使用此代码时,弹出窗口将在每个弹出窗口中仅包含最后一个客户的名称。有人知道如何确保使用正确用户的属性吗?
这是一个闭包问题,要解决它,您必须将$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);
}
);
}
循环后for
i
总是locationList.length - 1
。尝试使用本地i
添加 IIFE。例如,您可以通过将循环替换为locationList.forEach
来解决for
这是
臭名昭著的循环问题。由于您只是定义函数,而不是在 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
}
);
}
}
让我知道这是否有帮助。
这是一个范围问题。您的i
将更新,稍后,当您单击弹出窗口时,它将读取i
的最后一个值。
你应该把你的条件放在一个函数for
,该函数接受参数i
:
function getCoordinates(locationList) {
for (var i = 0; i < locationList.length; i++) {
conditionalGet(i);
}
function conditionalGet(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);
});
}
}
}
相关文章:
- '这'在使用之前分配给了一个var
- JavaScript 在内部函数中保留一个 var
- jQuery-如何使var文本可点击,该文本放置在由更多元素组成的另一个var中(var,checkbox)
- 如何创建<p>标记,并在我单击它时将其分配给一个var
- 在 JavaScript 中,当一次声明多个变量时,仅使用一个 var 语句是否有内存优势
- 为什么我已经定义的全局变量被IE8中的另一个var语句覆盖
- Javascript:在“this”关键字之前有一个“var”关键字
- JS:我应该在点击(或等效)事件中设置一个var/let吗?
- Angularjs.then函数创建一个var以传递到外部.then
- 如何为路由实现另一个var参数名称
- 用javascript创建一个var;修改脚本以创建var用法
- 另一个var中的setDate方法返回不同的值
- 保护API令牌,使其成为我的index.js中的一个var
- 一个Var,多个createElement
- 你能从数组中调用一个var,而不是它的值吗
- 使用Restangular并尝试从$scope中为一个var设置多个参数
- 如何在jquery或javascript中连接另一个var字符串中的var
- 我如何定义一个var作为对象从对象在for循环
- 为什么我们需要使用一个“var”来定义许多变量?
- 为什么可以't我使用ajax将一个var从php导入到js