ros*_*lld 0 dom mapbox-gl mapbox-gl-js
我正在尝试创建一个自定义按钮,以显示在弹出窗口上,生成动态链接(URL).由于时间原因,我似乎无法通过.setHTML执行此操作,无法在运行时将按钮绑定到函数.所以我想我会尝试新的.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);
};
Run Code Online (Sandbox Code Playgroud)
此函数通过.setHTML添加html
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;
}
Run Code Online (Sandbox Code Playgroud)
此函数希望通过.setDOMContent添加DOM内容
function ClickedGameObject2(feature){
document.getElementById('btn-collectobj').addEventListener('click', function()
{
console.log("clicked a button");
AddGameObjectToInventory(feature.geometry.coordinates);
});
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试将来自features.geometry.coordinates的变量传递给函数AddGameObjectToInventory()
单击对象时出现的错误(以便生成弹出窗口)
Uncaught TypeError: Cannot read property 'addEventListener' of null
Run Code Online (Sandbox Code Playgroud)
Popup#setHTML 获取表示某些HTML内容的字符串:
var str = "<h1>Hello, World!</h1>"
popup.setHTML(str);
Run Code Online (Sandbox Code Playgroud)
而Popup#setDOMContent采取实际的HTML节点.即:
var h1 = document.createElement('h1');
h1.innerHTML="Hello, World";
popup.setDOMContent(h1);
Run Code Online (Sandbox Code Playgroud)
这两个代码片段都会产生相同的Popup HTML内容.您不希望在单个弹出窗口中使用这两种方法,因为它们是两种不同的方法来执行相同的操作.
您共享的代码中的问题是您尝试使用setDOMContent向您的按钮添加事件侦听器,但是Popup一旦将弹出DOM内容添加到该按钮,您就不需要访问该对象来添加事件侦听器地图.这是我认为您正在尝试做的工作版本:https://jsfiddle.net/h4j554sk/