简体   繁体   English

在Leaflet中访问标记图标的HTMLElement

[英]Accessing the HTMLElement of a marker's icon in Leaflet

I have some markers with custom icons (DivIcons) on my map. 我的地图上有一些带有自定义图标(DivIcons)的标记。

When I click on one marker, I want to access to the HTMLElement of the icon, to add or remove classes. 当我点击一个标记时,我想访问图标的HTMLElement,添加或删除类。

The only way I have found to access the HTMLElement is the _icon property. 我发现访问HTMLElement的唯一方法是_icon属性。 I understand it's a private property, but I can't find another way. 我知道这是私人财产,但我找不到另一种方式。

The options.icon returns me the icon object (used by many markers), not the concrete HTMLElement for this marker. options.icon返回图标对象(由许多标记使用),而不是此标记的具体HTMLElement。

Do you know a safe way to access to the HTMLElement of a marker ? 您是否知道一种安全的方式来访问标记的HTMLElement?

Unfortunately, JavaScript does not have native support for private properties. 不幸的是,JavaScript没有对私有属性的本机支持。 However, there are several techniques to emulate them: one using prefixes, the other closures. 但是,有几种技术可以模拟它们:一种使用前缀,另一种使用前缀。

The use of an underscore prefix is just a coding convention and is not enforced by the language: there is nothing to prevent a user from directly accessing a property that is "supposed to be private". 使用下划线前缀只是一种编码约定,并不是由语言强制执行的:没有什么可以阻止用户直接访问“应该是私有的”属性。 This method is not safe, and it serves only as a guideline for client code. 此方法不安全,仅作为客户端代码的准则。 So I don't think that any harm can be done by accessing _icon property. 所以我认为通过访问_icon属性不会造成任何伤害。

If a property is supposed to be private without possibility to be accessed from the outside, it is usually set as a local variable of a certain scope without being binded to the context. 如果属性应该是私有的,不可能从外部访问,则通常将其设置为某个范围的局部变量,而不绑定到上下文。 This type of variables can be accessed from the outside only with the help of closures, and if they are not defined, the variable can't be accessed. 这种类型的变量只能在闭包的帮助下从外部访问,如果没有定义,则无法访问变量。

I have found a documented way to access it : 我找到了一种记录方式来访问它:

Since I am in a "click" event, I can access the marker's HTMLElement with event.originalEvent.target in the callback. 由于我处于“点击”事件中,我可以在回调中使用event.originalEvent.target访问标记的HTMLElement。

http://leafletjs.com/reference.html#event-objects http://leafletjs.com/reference.html#event-objects

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM