Jen*_*sen 14 javascript mapbox vue.js
我已经为MapBox地图添加了自定义按钮,他们正确购物.但是当我添加一个点击监听器时,它不起作用.我在控制台中看到没有错误.
代码如下所示:
const currentLocationControl = new CustomControl('current-location-control', 'GPS');
this.map.addControl(currentLocationControl, 'top-left');
document.getElementById('test').addEventListener('click', function (e) {
alert('test');
});
Run Code Online (Sandbox Code Playgroud)
我在mounted方法中执行此代码vue.js.
CustomControl:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我console.log(document.getElementById('test'));在控制台(测试div)中看到预期结果时.
那么可能会发生什么?
该元素很可能还不存在,具体取决于map.addControl工作原理。
也许如果你在你的方法中创建了一个方法CustomControl来返回容器,而不是使用document.getElementById你会使用类似currentLocationControl.getContainer()?
或者setAction您CustomControl喜欢的
setAction(action) {
this.container.addEventListener('click', action);
}
Run Code Online (Sandbox Code Playgroud)