单击 Leaflet Popup 内的链接并执行 Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13698975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Click link inside Leaflet Popup and do Javascript
提问by Josh
I have a leaflet map up and running. It overlays a series of polygons (via GeoJSON) on the map and attaches popups to each polygon. Each of the popups display information about that polygon.
我有一个传单地图正在运行。它在地图上覆盖一系列多边形(通过 GeoJSON)并将弹出窗口附加到每个多边形。每个弹出窗口都显示有关该多边形的信息。
I'd like to have inside the popup a link that, when clicked, runs a javascript function that pulls further smaller polygons via AJAX and shows them.
我想在弹出窗口中有一个链接,当点击该链接时,会运行一个 javascript 函数,该函数通过 AJAX 拉取更小的多边形并显示它们。
I can't get the script to catch a click on the link via the normal jQuery/Javascript click events. Here's what I mean by normal (the following doesn't work):
我无法让脚本通过普通的 jQuery/Javascript 点击事件来捕捉链接上的点击。这就是我所说的正常(以下不起作用):
$('a .smallPolygonLink').click(function(e){
console.log("One of the many Small Polygon Links was clicked");
});
The bindPopup part is as follows. It runs on each polygon when made and it pops up correctly on clicking on a polygon. It does show the link, just won't run the above code on click.
bindPopup 部分如下。它在创建时在每个多边形上运行,并在单击多边形时正确弹出。它确实显示了链接,只是不会在点击时运行上面的代码。
var popupContent = "Basic Information..." + '<a class="smallPolygonLink" href="#">Click here to see the smaller polygons</a>';
layer.bindPopup(popupContent);
Here's a JSFiddle illustrating the example, though in a far simpler form. http://jsfiddle.net/2XfVc/4/
这是一个 JSFiddle 说明了这个例子,虽然形式要简单得多。http://jsfiddle.net/2XfVc/4/
回答by Asad Saeeduddin
The link element inside the popup is being dynamically generated from your markup each time the popup is opened. That means the link doesn't exist when you're trying to bind the handler to it.
每次打开弹出窗口时,弹出窗口内的链接元素都会根据您的标记动态生成。这意味着当您尝试将处理程序绑定到链接时,该链接不存在。
The ideal approach here would be to use onto delegate event handling to the popup element or an ancestor of it. Unfortunately, the popup prevents event propagation, which is why delegating event handling to any static elements outside the popup won't work.
这里的理想方法是on将事件处理委托给弹出元素或其祖先。不幸的是,弹出窗口阻止了事件传播,这就是将事件处理委托给弹出窗口之外的任何静态元素不起作用的原因。
What you can do is preconstruct the link, attach the handler, and then pass it to the bindPopupmethod.
您可以做的是预先构造链接,附加处理程序,然后将其传递给bindPopup方法。
var link = $('<a href="#" class="speciallink">TestLink</a>').click(function() {
alert("test");
})[0];
marker.bindPopup(link);
Here is a demonstration: http://jsfiddle.net/2XfVc/7/
这是一个演示:http: //jsfiddle.net/2XfVc/7/
In general, to insert any sort of complex markup with multiple event handlers, use the folowing approach:
通常,要插入具有多个事件处理程序的任何类型的复杂标记,请使用以下方法:
// Create an element to hold all your text and markup
var container = $('<div />');
// Delegate all event handling for the container itself and its contents to the container
container.on('click', '.smallPolygonLink', function() {
...
});
// Insert whatever you want into the container, using whichever approach you prefer
container.html("This is a link: <a href='#' class='smallPolygonLink'>Click me</a>.");
container.append($('<span class="bold">').text(" :)"))
// Insert the container into the popup
marker.bindPopup(container[0]);
Here is a demo: http://jsfiddle.net/8Lnt4/
这是一个演示:http: //jsfiddle.net/8Lnt4/
See this Git issuefor more on event propagation in leaflet popups.
有关传单弹出窗口中事件传播的更多信息,请参阅此 Git 问题。
回答by semiomant
While the Popup content wrapper prevents event propagation, events within the popup inner Markup propagate just fine. You can add events to popup elements when they are displayed on the map (and have become part of the DOM). Just watch for leaflet event popupopen.
虽然 Popup 内容包装器阻止了事件传播,但 Popup 内部标记中的事件传播得很好。当弹出元素显示在地图上(并且已成为 DOM 的一部分)时,您可以向它们添加事件。只需注意传单事件popupopen。
var map = L.map('map').setView([51.505, 10], 7); //for example
//the .on() here is part of leaflet
map.on('popupopen', function() {
$('a .smallPolygonLink').click(function(e){
console.log("One of the many Small Polygon Links was clicked");
});
});
This works like a charm for me. If your popup does not have a 'a .smallPolygonLink'the above code does nothing.
This code runs on every startup of a popup. However you don't have to worry that it attaches more than one handler to an element, since when the popup closes, the DOM nodes get thrown away.
这对我来说就像一种魅力。如果您的弹出窗口没有'a .smallPolygonLink'上面的代码,则什么都不做。此代码在每次弹出窗口启动时运行。然而,您不必担心它将多个处理程序附加到一个元素,因为当弹出窗口关闭时,DOM 节点会被丢弃。
There is a much more general way to do this. However, it involves eval(). Use at your own risk. But when AJAXloading partial pages that contain JS you run the same risks, so for your edification I present "executing JS inside your leaflet popups":
有一种更通用的方法可以做到这一点。然而,它涉及eval(). 使用风险自负。但是当 AJAX 加载包含 JS 的部分页面时,您会遇到相同的风险,因此为了您的启发,我提出“在您的传单弹出窗口中执行 JS”:
map.on('popupopen', function(){
var cont = document.getElementsByClassName('leaflet-popup-content')[0];
var lst = cont.getElementsByTagName('script');
for (var i=0; i<lst.length;i++) {
eval(lst[i].innerText)
}
});
demo: http://jsfiddle.net/tJGQ7/4/
演示:http: //jsfiddle.net/tJGQ7/4/
Now you can write:
现在你可以写:
var popup_content = 'Testing the Link: <a href="#" class="speciallink">TestLink</a><script> $(".speciallink").on("click", function(){alert("hello from inside the popup")});</script>';
marker.bindPopup(popup_content);
回答by Kiki Yang
That's what I find on the mapbox offical website: Create a click event in a marker popup with Mapbox.js and jQuery.The comment explains why we say $('#map')instead of $('#mybutton').
这就是我在 mapbox 官方网站上找到的内容:使用 Mapbox.js 和 jQuery 在标记弹出窗口中创建单击事件。评论解释了为什么我们说$('#map')而不是$('#mybutton')。
var marker = L.marker([43.6475, -79.3838], {
icon: L.mapbox.marker.icon({
'marker-color': '#9c89cc'
})
})
.bindPopup('<button class="trigger">Say hi</button>')
.addTo(map);
//The HTML we put in bindPopup doesn't exist yet, so we can't just say
//$('#mybutton'). Instead, we listen for click events on the map element which will bubble up from the tooltip, once it's created and someone clicks on it.
$('#map').on('click', '.trigger', function() {
alert('Hello from Toronto!');});
回答by jivanrij
I came across this problem, tried the solution above. But it didn't worked for me. Found the following pretty basic jquery solution.
我遇到了这个问题,尝试了上面的解决方案。但它对我不起作用。找到了以下非常基本的 jquery 解决方案。
// add your marker to the map
var my_marker = new L.marker([51.2323, 4.1231], {icon: my_icon});
var popup = L.popup().setContent('<a class="click" href="#">click</a>');
my_marker.addTo(map).bindPopup(popup);
// later on
jQuery("body").on('click','a.click', function(e){
e.preventDefault();
alert('clicked');
});
回答by SerzN1
You can check inner properties of popupobject, including _wrapperetc.
您可以检查popup对象的内部属性,包括_wrapper等。
map.on('popupopen', _bindPopupClick);
map.on('popupclose', _unbindPopupClick);
var _bindPopupClick = function (e) {
if (e.popup) {
e.popup._wrapper.addEventListener('click', _bindPopupClickHandler);
}
};
var _unbindPopupClick = function (e) {
if (e.popup) {
e.popup._wrapper.removeEventListener('click', _bindPopupClickHandler);
}
}`
回答by wandarkaf
You can use jQuery to select the canvaselement, but you'd have to use its own methods within the canvas. A decent start would be https://developer.mozilla.org/en/canvas_tutorial.
您可以使用 jQuery 来选择canvas元素,但您必须在画布中使用它自己的方法。一个不错的开始是https://developer.mozilla.org/en/canvas_tutorial。
回答by Dilip Kumar
mapbox JavaScript library has an event:
mapbox JavaScript 库有一个事件:
bindPopup('<button class="trigger">Say hi</button>');
addTo(map);
$('#map').on('click', '.trigger', function() {
alert('Hello from Toronto!');
});
https://www.mapbox.com/mapbox.js/example/v1.0.0/clicks-in-popups/
https://www.mapbox.com/mapbox.js/example/v1.0.0/clicks-in-popups/

