0

我有以下代码:

<body>
    <canvas id="canvas" height="300" width="300" style="border:1px solid" />
</body> 

<script>
    function maze(canvas){
       this.ctx = canvas[0].getContext("2d");
       canvas.mousedown(down);   
    }

    function down(e){
      alert(this.ctx);   
    }    
$(document).ready(function(e){   
   var m = new maze($('#canvas'))   
}); 
</script>

但是在向下函数中 this.ctx 是未定义的,有什么想法吗?(是的,我正在导入 jQuery 1.6.2)

4

1 回答 1

1

这里canvas指向一个 jquery 对象this并将指向迷宫实例。所以试试这个

function maze(canvas){
       canvas.data("ctx", canvas[0].getContext("2d"));
       canvas.mousedown(down);   
    }

    function down(e){
      alert($(this).data("ctx"));   
    }    
$(document).ready(function(e){   
   var m = new maze($('#canvas'))   
}); 
于 2011-08-03T21:43:29.193 回答