【发布时间】:2018-09-17 11:54:20
【问题描述】:
我已将自定义按钮添加到我的 MapBox 地图中,并且它们可以正确购物。然而 当我添加点击监听器时它不起作用。我在控制台中看不到任何错误。
代码如下所示:
const currentLocationControl = new CustomControl('current-location-control', 'GPS');
this.map.addControl(currentLocationControl, 'top-left');
document.getElementById('test').addEventListener('click', function (e) {
alert('test');
});
我在vue.js 的mounted 方法中执行此代码。
自定义控件:
export default class CustomControl {
constructor(className, text) {
this.className = className;
this.text = text;
}
onAdd(map){
this.map = map;
this.container = document.createElement('div');
this.container.id = 'test';
this.container.className = this.className;
this.container.textContent = this.text;
return this.container;
}
onRemove(){
this.container.parentNode.removeChild(this.container);
this.map = undefined;
}
}
当我console.log(document.getElementById('test')); 时,我在控制台(测试 div)中看到了预期的结果。
那么这里会发生什么?
【问题讨论】:
-
这很可能是因为您在 javascript 中构建它,因此当您尝试绑定使用时它在 DOM 中不可用。改为使用最近的静态父元素的事件委托
-
任何人????!?!?!
-
你尝试过我告诉你的吗?
-
@ohgodwhy 它在 vue.js 组件中,所以没有静态父级对吗?感谢您的帮助。
-
只需在该特定行放置一个断点并检查该元素是否真的存在。此外,可以绑定事件,但按钮可能会出现在地图下方,因此您实际上单击的是地图而不是按钮。你有正确的 z 索引吗?
标签: javascript vue.js mapbox