我想將全局變量mouseX,mouseY分配給函數內部的事件偵聽器。當我嘗試在另一個函數中使用變量時,它們會返回undefined。函數中未定義的全局變量
我知道這可能是一個問題與變量的範圍被分配給,但一直無法弄清楚,我寫的任何簡單的測試代碼不會重現該問題。
這是什麼造成的?
的javascript:
var mouseX, mouseY;
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var bars = [];
for(var i = 0; i < 30; i++)
bars[i] = new Bar(ctx, 100+i*10, canvas.height, 5, 150);
for(var i = 0; i < bars.length; i++){
bars[i].checkMouse();
bars[i].display();
}
function Bar(ct, x, y, w, h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.y -= this.h;
this.display = function() {
ct.rect(this.x, this.y, this.w, this.h);
ct.fill();
}
this.checkMouse = function() {
//if(mouseX >= this.x && mouseX <= this.x + this.w){
//this.y = mouseY; this.h = height-mouseY;
console.log(mouseX); //////mouseX is undefined?
//}
}
}
function getMouse(event) {
mouseX = event.offsetX;
mouseY = event.offsetY;
var coords = "mouseX: " + mouseX + ", mouseY: " + mouseY;
document.getElementById('display').innerHTML = coords;
}
HTML:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
canvas{
background-color: #e6e6e6;
position:relative;
}
</style>
</head>
<body>
<div id="display"> </div>
<canvas onmousemove="getMouse(event)" id="myCanvas" width="500" height="200">
<script src="myscript.js"></script>
</body>
</html>
在函數中傳遞mouseX this.checkMouse = function(mouseX){// – Bugfixer
這不是OP問題的答案。 –
在事件甚至運行之前,您沒有設置'mouseX'和'mouseY',直到您調用'getMouse',但您只調用bars [i] .checkMouse();'* *。 – h2ooooooo