在循环中填充javascript变量,以在循环外用于图标定义 [英] Populate javascript variable in loop to use for icon definition outside loop

查看:47
本文介绍了在循环中填充javascript变量,以在循环外用于图标定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用传单api创建地图并在其上放置标记.我使用了在此处找到的简单标记功能: https://dotscrapbook.wordpress.com/2014/11/28/simple-numbered-markers-with-leaflet-js/

I'm using leaflet api to create a map and place markers on it. I've used a simple marker function found here: https://dotscrapbook.wordpress.com/2014/11/28/simple-numbered-markers-with-leaflet-js/

因此此代码段有效:

var numberIcon = L.divIcon({
 classname: "number-icon",
 iconsize: [25, 41],
 iconAnchor: [3, -40],
 html: 11
});

for (i=0; i<points.length; i++)

{

L.marker(points[i], {icon: numberIcon}).addTo(map1);
}

但这不是(但是我需要它,所以我可以在for循环中填充"number"变量,然后将其发送回numberIcon.)

But this does not (but I need it to so I can populate the "number" variable within the for loop, sending it back up to the numberIcon).

var number;

var numberIcon = L.divIcon({
 classname: "number-icon",
 iconsize: [25, 41],
 iconAnchor: [3, -40],
 html: number
});

for (i=0; i<points.length; i++)

{
number = '11';

L.marker(points[i], {icon: numberIcon}).addTo(map1);
}

我一定没有把范围弄对.你有什么建议吗?谢谢!

I must not be getting the scope right. Do you have any suggestions? Thanks!

推荐答案

numberIcon 对象的 html 选项分配了 value 创建时(即循环之前)的 number .因此, html undefined .以后将不重新评估此分配,因此无论变量 number 变为什么,它都将保持为 undefined .

The html option of your numberIcon object is assigned the value of number at creation, i.e. before your loop. So html is undefined. This assignment is not re-evaluated later on, so it remains at undefined, no matter what the variable number becomes.

您可以尝试直接在循环中重新分配 html 选项( numberIcon.options.html ='11'),这样,如果您的标记创建了它的图标立即,它将使用 html 的更新值.但是,正如用户6502所指出的那样,您所有的标记现在都使用完全相同的图标对象.因此,如果由于某种原因,其中一个标记需要重新创建其图标元素(例如,将标记从地图上删除并重新添加回去时会发生这种情况),它将读取 html 的最后一个值,这可能不是您想要的.

You could try re-assigning directly the html option within your loop (numberIcon.options.html = '11'), so that if your marker creates its icon right away, it will use an updated value of html. However, as pointed out by user 6502, all your markers now use the exact same icon object. So if for some reason, one of the marker needs to re-create its icon element (this happens for example when the marker is removed from map and added back), it will read the last value of html, which is probably not what you want.

演示: http://jsfiddle.net/ve2huzxw/6/

通常在Leaflet中建议为每个标记实例化一个图标,以避免出现此问题.

It is usually recommended in Leaflet to instantiate one icon per marker, to avoid this issue.

有关示例,请参见用户6502的答案.

See user 6502's answer for an example of doing so.

这篇关于在循环中填充javascript变量,以在循环外用于图标定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆