不同事件侦听器中的变量可访问性
Variable accessibility in different event listeners
我有三个JavaScript事件——mouseup
、mousedown
和mousemove
。对每个事件调用不同的函数。我希望这三个函数共享一个相同的变量,该变量在这些函数之外被分配了一个初始值。
能做到吗
sarfraz要求提供代码,它在这里:
if(window.addEventListener) {
window.addEventListener('load', function () {
var canvas, context;
// Initialization sequence.
var z=false;
function init () {
// Find the canvas element.
canvas = document.getElementById('imageView');
if (!canvas) {
alert('Error: I cannot find the canvas element!');
return;
}
if (!canvas.getContext) {
alert('Error: no canvas.getContext!');
return;
}
// Get the 2D canvas context.
context = canvas.getContext('2d');
if (!context) {
alert('Error: failed to getContext!');
return;
}
// Attach the mousemove event handler.
canvas.addEventListener('mousedown',ev_mousedown,false);
canvas.addEventListener('mouseup',ev_mouseup,false);
canvas.addEventListener('mousemove', ev_mousemove, false);
}
//The mouseup
function ev_mouseup(ev)
{
z=false;
}
//The mousedown
function ev_mousedown(ev)
{
z=true;
}
// The mousemove event handler.
var started = false;
function ev_mousemove (ev) {
var x, y;
// Get the mouse position relative to the canvas element.
if (ev.layerX || ev.layerX == 0) { // Firefox
x = ev.layerX;
y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
x = ev.offsetX;
y = ev.offsetY;
}
// The event handler works like a drawing pencil which tracks the mouse
// movements. We start drawing a path made up of lines.
if (!started) {
if(z){
context.beginPath();
context.moveTo(x, y);
started = true;
}
} else {
context.lineTo(x, y);
context.stroke();
}
}
init();
}, false); }
使用其中之一:
- 全球
- 围绕变量和事件处理程序的闭包
正如昆汀所说,你可以尝试类似的东西
//Create a global object
//Best practice is to use a single global namespace
//Prevents pollution of your variables
var myNamespace = {myKey: 'some initial value'};
$('#id').mouseup(do something with myNamespace)
$('#id').mousedown (do something with myNamespace)
$('#id').mousemove(do something with myNamespace)
您可以使用全局变量,除非您在事件函数中声明了相同的变量名,否则它将覆盖全局变量;
var test; //global var
$().mouseup(function(){
test='mouseup';
})
.mousedown(function(){
test = 'mousedown';
})
.mousemove(function(){
var test; //overwrite global variable
test = 'mousemove';
//in this case global test keeps the previous value
//while local test has 'mousemove' value
});
相关文章:
- 如何从字符串变量访问对象属性
- 无法使用变量访问数据 JSON
- D3:使用变量访问绑定数组中的对象
- JavaScript 变量访问错误
- CanvasJS-访问变量-访问属性toString的权限被拒绝
- 如何使用javascript数据对象?如何通过变量访问条目
- 如何使用变量访问对象属性
- 使用变量访问对象的属性
- 如何使用包含对象键名的变量访问对象属性
- 为什么通过缓存变量访问 DOM 更快
- 将 PHP 变量访问到外部 JavaScript 文件中
- 使用变量访问 Javascript 中的对象信息
- 使用变量访问 JSON 属性(字符串)
- 如何在 yii 中从 javascript 变量访问文本字段输入
- 如何使用 javascript 变量访问模型属性
- 根据 HighCharts 对象的变量访问数组的元素
- 使用动态变量访问 Meteor 中另一个变量的值
- 如何通过绑定的控制器变量访问服务的属性
- Angular JS工厂和变量访问
- 使用变量访问对象的值