开发者

Problems with jQuery event binding

  $("#canvas").mousedown(function(e) {
  for(i=0; i<allPoints[0].length; i++) {
   var pointX = controlPoint[i].x;
   var pointY = controlPoint[i].y;
   var mouseX = e.pageX - this.offsetLeft;
   var mouseY = e.pageY - this.offsetTop;
   if(pointX + 5 > mouseX && pointX - 5 < mouseX && pointY + 5 > mouseY && pointY - 5 < mouseY) {
    var testest = i;
    $(this).bind('mousemove', function(e) {
    //'i' is undefined here
    //'testest' is defined
     controlPoint[testest].x = e.pageX - this.offsetLeft;
     controlPoint[testest].y = e.pageY - this.offsetTop;
    });
   }
  }
 }).mouseup(function(e){
  $(this).unbind('mousemove');
 });

For some reason when I try to use the variable 'i' from the for loop inside of my mousemove function it is undefined. If I assign it to another variable before that works for some reason, but I don't want to do that because it seems unnecessary. Any help would be gr开发者_StackOverflow中文版eatly appreciated.


I can't know for sure, but I believe it's, because your i variable is global. Always declare a variable that should not be global with a var keyword. For example,

for(var i=0; i<allPoints[0].length; i++) {

I think your application modifies the variable i somewhere else and that is the reason why assigning it to another variable seems to solve your problem. The real solution here is to use a local variable with a var keyword.


The fact that i is undefined is very bizarre. The only way this can happen is if it's being set to undefined somewhere else in your code. If the global variable i is never used anywhere else, then the value of i will always be equivalent to allPoints[0].length inside your 'mousemove' callback because you're creating a closure around the i variable, which will be set to allPoints[0].length by the end of the mousedown callback. Also, be aware that testest will be hoisted to the top of the mousedown callback, so the value of testest inside the mousemove callback will always be the last value that was set inside the mousemove callback.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜