【问题标题】:How to add a click event on a button created with javascript in a Ol3 popup?如何在 Ol3 弹出窗口中使用 javascript 创建的按钮上添加点击事件?
【发布时间】:2017-01-26 18:55:08
【问题描述】:

我正在使用 Openlayers 3 开发网络地图应用程序,我在地图上显示要素(点),当我单击它们时,我会显示一个弹出窗口,其中我添加了一个按钮。这是弹出窗口和按钮代码:

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);
    }   
});

之后我在stackoverflow中看到了一些类似的问题,我尝试使用这段代码在事件触发时启动一个函数:

$(document).on("click", "#popupButton", function(){
      alert(nearest_feature(my_position)); 
});

问题是事件没有被触发,我尝试用“#map”(这是显示地图的 div)替换文档,但仍然没有。

如何在弹出窗口中触发该按钮的事件?

【问题讨论】:

    标签: javascript jquery html openlayers-3


    【解决方案1】:

    我使用了@Jesper Højer 和@Marius 在他们的答案中给出的代码,起初它不起作用,所以我将它添加到:

    map.on('singleclick', function(evt){
    ---------
    $("#popupButton").on("click", function(){
          alert(nearest_feature(my_position)); 
    });
    }
    

    现在触发了事件

    【讨论】:

    • 但是现在你每次点击地图时都要设置事件监听器??
    • 你能说 $(document).ready(function() { $("#popupButton").on("click", function(){ alert(nearest_feature(my_position)); }) ; 地图外.on.
    • 因为仅当我单击地图上的某个要素然后创建#popupButton 时才会出现弹出窗口。我想现在应该没问题了,还是我错过了什么?
    • 啊,我明白你现在要做什么了 :) 你也可以这样设置然后 map.on('click', '#popupButton', function() {alert(nearest_feature(我的位置));});
    • 不幸的是,我也尝试过,我什至将事件委托给 html 页面的许多其他静态元素,但仍然没有。令人惊讶的是,当我将该事件包含在它起作用的地图的单击事件中时
    【解决方案2】:

    我尝试实现它,我认为您使用它的方式,它有效吗?

    <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>');
      });
    
    });
    

    https://jsfiddle.net/d9eubeeu/

    【讨论】:

    • 这是我尝试的第一件事,但事件仍然没有触发
    • 我忘了提到弹出窗口本身不是 html 元素,我在 javascript 文件中将其声明为 ol.Overlay.Popup();来自 Openlayers 3。我不知道如何以这种方式将按钮附加到它
    【解决方案3】:

    会不会是事件冒泡发生了?地图上已经有一个监听器。弹出窗口中可能也有一个。如果您将事件作为参数传递给您的函数,您可以使用:

    event.stopPropagation();
    

    【讨论】:

      猜你喜欢
      • 2021-01-31
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      相关资源
      最近更新 更多