简体   繁体   English

如何使 leaflet 中的外部函数可以访问 in.bindpopup 中的元素?

[英]How to make a element in .bindpopup accessible for external functions in leaflet?

I have a function that feeds variables to a Popup, which is working so far.我有一个 function 将变量提供给一个弹出窗口,到目前为止它正在工作。 Now I inserted a button in this Popup and want some function to run when clicked on this, but the the object is not accessible for my external function.现在我在此弹出窗口中插入了一个按钮,并希望在单击此按钮时运行一些 function,但是我的外部 function 无法访问 object。 How can I rewrite this function, to access the single elements more easy?如何重写此 function,以更轻松地访问单个元素?

marker:标记:

var marker      = L.marker([data[i].lat, data[i].lng], {icon: greenIcon}).addTo(map);
marker.bindPopup(id + "<br>" + species + "<br>" + diameter + "<br>" + quality + "<br>" + damage + "<br>" + notes + "<br>" + "<br>" +
'<input type="submit" id = "delete" name="action" data-value = " + id + " value="Delete" method = "post"/>');
        

function: function:

<script type="text/javascript">
    $(function(){
        $('#delete').click(function(d){
            
        alert("deleted")
    });
});
</script>

You have to add the listener after the Popup is opened:打开 Popup 后,您必须添加侦听器:

marker.on('popupopen',function(e){
    $('#delete').click(function(d){ 
        alert("deleted")
    });
}

As you have figured out, what you provide to bindPopup in your code is just an HTML string that you cannot directly use to attach an event listener to.正如您所知道的,您在代码中提供给bindPopup的只是一个 HTML 字符串,您不能直接使用它来附加事件侦听器。

You have several possible solutions for this:您有几种可能的解决方案:

  • build an HTML Element to pass to bindPopup instead of a String, so that you can manipulate it as an object构建一个 HTML 元素以传递给bindPopup而不是字符串,以便您可以将其作为 object 进行操作

  • defer the attachment of your listener to after the popup is open, hence the HTML string is converted to a DOM element on the page将侦听器的附件推迟到弹出窗口打开后,因此 HTML 字符串将转换为页面上的 DOM 元素

  • use event delegation to attach your listener to a parent element instead, which already exists in DOM, but filtering events to target your future button使用事件委托将您的侦听器附加到父元素,该元素已存在于 DOM 中,但过滤事件以定位您的未来按钮

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.事件委托允许我们将单个事件侦听器附加到父元素,该事件侦听器将为匹配选择器的所有后代触发,无论这些后代现在存在还是将来添加。

With jQuery this could be like:使用 jQuery 这可能是这样的:

$("body").on("click", "#delete", myListenerFunction);

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

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