2017-02-07 49 views
0

我试图创建一个自定义的按钮出现在生成一个动态链接(网址)弹出。由于时间原因,我似乎无法通过.setHTML执行此操作,因此无法在运行时将按钮绑定到函数。所以,我想我会在网上尝试新望.setDOMContent 有零信息,这个功能是如何工作的。我想知道是否有人有这样一个例子,一个按钮被添加到可以运行一个函数并发送数据的弹出窗口中。Mapbox GL弹出.setDOMContent例如

这里是我的设置此功能非常差的尝试。

这个函数创建弹出

function GameObjectPopup(myObject) { 
    var features = map.queryRenderedFeatures(myObject.point, { 
     layers: ['seed'] 
    }); 

    if (!features.length) { 
     return; 
    } 

    var feature = features[0]; 
    // Populate the popup and set its coordinates 
    // based on the feature found. 
    var popup = new mapboxgl.Popup() 
     .setLngLat(feature.geometry.coordinates) 
     .setHTML(ClickedGameObject(feature)) 
     .setDOMContent(ClickedGameObject2(feature)) 
     .addTo(map); 
}; 

此功能通过.setHTML

function ClickedGameObject(feature){ 
    console.log("clicked on button"); 
    var html = ''; 

    html += "<div id='mapboxgl-popup'>"; 
    html += "<h2>" + feature.properties.title + "</h2>"; 
    html += "<p>" + feature.properties.description + "</p>"; 
    html += "<button class='content' id='btn-collectobj' value='Collect'>"; 
    html += "</div>"; 
    return html; 
} 

此功能要通过.setDOMContent

function ClickedGameObject2(feature){ 
    document.getElementById('btn-collectobj').addEventListener('click', function() 
    { 
     console.log("clicked a button"); 
     AddGameObjectToInventory(feature.geometry.coordinates); 
    }); 
} 
添加DOM内容添加HTML

我想管变量从features.geometry.coordinates到设定的功能离子AddGameObjectToInventory()

在物体上点击时,我发现了错误(以便正在生成弹出)

Uncaught TypeError: Cannot read property 'addEventListener' of null 

回答

4

Popup#setHTML使用表示一些HTML内容的字符串:

var str = "<h1>Hello, World!</h1>" 
popup.setHTML(str); 

Popup#setDOMContent需要实际的HTML节点。即:

var h1 = document.createElement('h1'); 
h1.innerHTML="Hello, World"; 
popup.setDOMContent(h1); 

这两个代码片段都会导致相同的Popup HTML内容。您不希望在单个弹出窗口中使用这两种方法,因为它们有两种不同的方式来执行相同的操作。

您分享的代码中存在的问题是,您尝试使用setDOMContent向您的按钮添加事件侦听器,但您无需访问Popup对象即可在弹出DOM后添加事件侦听器内容已添加到地图中。这里是什么,我认为你正在试图做一个工作版本:https://jsfiddle.net/h4j554sk/