[英]Why does my javascript mouse event not fire?
Here's what I thought was simple code: 我认为这是简单的代码:
<html>
<head>
<script>
function Foobar(id) {
self = this;
self.id = id;
self.canvas = document.createElement('canvas');
self.canvas.style.border = '1px solid black';
document.body.appendChild(self.canvas);
self.canvas.addEventListener('mousedown', self.onMouseDown, true);
self.onMouseDown = function(e) {
console.log(self.id);
}
}
var s1, s2;
function onLoad() {
s1 = new Foobar(1);
s2 = new Foobar(2);
}
</script>
</head>
<body onload='onLoad()'>
</body>
</html>
Why does the console not pop up with the id number? 为什么控制台没有弹出ID号?
Here's a fiddle: http://jsfiddle.net/VRn7v/ 这是一个小提琴: http : //jsfiddle.net/VRn7v/
You must assign the method on self
before binding the event listner 绑定事件列表器之前,必须在
self
上分配方法
FIXED 固定
http://jsfiddle.net/landau/VRn7v/3/ http://jsfiddle.net/landau/VRn7v/3/
self
is a property of the window
object and is generally a bad variable name. self
是window
对象的属性,通常是错误的变量名。 Also, your self
variable is an implicit global because you are missing the var
keyword. 另外,您的
self
变量是隐式全局变量,因为您缺少var
关键字。 Finally, you are binding the event handler before it is declared. 最后,在声明事件处理程序之前将其绑定。
function Foobar(id) {
var that = this; // pick a better name, and use "var"
that.id = id;
that.canvas = document.createElement('canvas');
that.canvas.style.border = '1px solid black';
document.body.appendChild(that.canvas);
that.onMouseDown = function(e) {
console.log(self.id);
}; // missing semicolon
// bind the handler after declaring it
that.canvas.addEventListener('mousedown', that.onMouseDown, true);
}
self.canvas.addEventListener('mousedown', self.onMouseDown, true);
In this line, self.onMouseDown
is undefined
, because you assign it only afterwards. 在这一行中,
self.onMouseDown
是undefined
,因为您仅在之后分配它。 Possible quickfixes to get it work: 使它工作的可能的快速修复程序:
onMouseDown
function to the prototype (bad, no local self
in the scope) onMouseDown
函数移至原型(错误,作用域中没有本地self
) self.onMouseDown
, but self.canvas.onmousedown
(cross-browser-safe with traditional event registration) self.onMouseDown
,而self.canvas.onmousedown
使用self.onMouseDown
(使用传统事件注册的跨浏览器安全) Also, your self
variable is global. 另外,您的
self
变量是全局变量。 With a working handler attachment, both clicks will log "2"
. 使用有效的处理程序附件,两次单击都将记录为
"2"
。 And, the self
variable is not needed in the most places you use it - the only need for it is in the event handler. 而且,在大多数使用
self
变量的地方都不需要self
变量-唯一的需要就是事件处理程序。
Corrected fiddle: http://jsfiddle.net/VRn7v/2/ 更正了小提琴: http : //jsfiddle.net/VRn7v/2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.