改变 addEventListener 内部的变量
2018-08-08
62
这是我的问题,我试图在按下鼠标时将新坐标添加到 2D 数组中,但我无法找到如何成功访问事件侦听器内的变量。我尝试了几种方法,但找不到如何使其工作。
myGameArea.canvas.addEventListener('click', function(){
var MousesX = event.clientX+55;
var MousesY = event.clientY+55;
}, false);
ConnectionAdd(MouseX,MouseY,Connections,viewH);
这是它所说的
ReferenceError: MouseX is not defined at draw
顺便说一句,这是最基本的测试,但它最能描述我想要做的事情。
2个回答
好的……首先,您忘记在回调中添加
event
参数:
myGameArea.canvas.addEventListener('click', function (event) {
var MousesX = event.clientX+55;
var MousesY = event.clientY+55;
}, false);
ConnectionAdd(MouseX,MouseY,Connections,viewH);
其次,您必须将 ConnectionAdd 函数 移到回调内部。这不仅是因为在该回调之外,您的变量 MouseX 和 MouseY 不可访问,而且主要是因为该函数也必须异步执行,因此在触发回调时执行,而不是在事件侦听器定义之后立即执行。
myGameArea.canvas.addEventListener('click', function (event) {
var MousesX = event.clientX+55;
var MousesY = event.clientY+55;
ConnectionAdd(MouseX,MouseY,Connections,viewH);
}, false);
Vladislav Ladicky
2018-08-08
只需在点击事件之外定义它们,然后像​​这样在里面设置它们:
var MousesX = 0
var MousesY = 0
document.getElementById('demo').addEventListener('click', function(e) {
MousesX = e.clientX + 55;
MousesY = e.clientY + 55;
console.log(MousesX)
console.log(MousesY)
}, false);
document.getElementById('demo2').addEventListener('click', function(e) {
console.log(MousesX)
console.log(MousesY)
}, false);
<p id="demo">asdf</p>
<p id="demo2">demo2 first click is zeros clicks will be what was stored on the last demo click</p>
Scath
2018-08-08