I am working on a web mapping app with Openlayers 3, I display features (points) on the map and when I click on them I display a popup where I added a button. Here is the popup and the button code first :
map.on('singleclick', function(evt) {
popup.hide();
popup.setOffset([0, 0]);
// Attempt to find a feature in one of the visible vector layers
var feature = map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
return feature;
});
if (feature) {
var coord = feature.getGeometry().getCoordinates();
var props = feature.getProperties();
var info = "<input type='button' id='popupButton' value='Get here ?' />" ;
// Offset the popup so it points at the middle of the marker not the tip
popup.setOffset([0, -22]);
popup.show(coord, info);
}
});
After that I saw some similar questions in stackoverflow and I tried this code to launch a function when the event is fired:
$(document).on("click", "#popupButton", function(){
alert(nearest_feature(my_position));
});
the problem is that the event isn't fired, I tried replacing document with '#map' ( which is the div where the map is shown) but still nothing.
How can I trigger the event for that button inside the popup ?
I tried implementing it, the way I think you are using it, and it worked?
<div id='container'>
<button id="AddDynamicBtn">
Add Dynamic Btn
</button>
</div>
$(document).ready(function() {
$('#container').on('click','#DynamicBtn', function() {
alert('TEST');
});
$('#AddDynamicBtn').on('click',function() {
$('#container').append('<button id="DynamicBtn">Dynamic Btn</button>');
});
});
I used the code that @Jesper Højer and @Marius gave in their answers it didn't work at first so I added it in the:
map.on('singleclick', function(evt){
---------
$("#popupButton").on("click", function(){
alert(nearest_feature(my_position));
});
}
and it worked now the event is triggered
Could it be that event bubbling is taking place? There is already a listener on the map. Potentially there might also be one on the popup. If you pass in the event as a parameter to your function you could use:
event.stopPropagation();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.