gpt4 book ai didi

javascript - Mapbox 事件监听器

转载 作者:可可西里 更新时间:2023-11-01 01:54:08 27 4
gpt4 key购买 nike

我已将自定义按钮添加到我的 MapBox map ,他们正确购物。然而当我添加点击监听器时,它不起作用。我在控制台中没有看到任何错误。

代码如下所示:

const currentLocationControl = new CustomControl('current-location-control', 'GPS');

this.map.addControl(currentLocationControl, 'top-left');

document.getElementById('test').addEventListener('click', function (e) {
alert('test');
});

我在 vue.jsmounted 方法中执行这段代码。

自定义控件:

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)中看到了预期的结果。

enter image description here

那么这里可能发生了什么?

最佳答案

要确保点击事件绑定(bind)到正确的元素,您可以改为在类声明中绑定(bind)事件。

将点击事件的回调传递给 CustomControl

const clickCallback = function(e) {
alert(test);
};

const currentLocationControl = new CustomControl(
"current-location-control",
"GPS",
clickCallback
);

类声明:

// add clickCallback to constructor
export default class CustomControl {
constructor(className, text, clickCallback) {
//...
}

onAdd(map) {
//...
this.container.onclick = clickCallback;
//...
}
}

关于javascript - Mapbox 事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49709971/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com