2011-08-03 22 views
0

我有以下代碼:添加監聽器,jQuery對象的構造

<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)

回答

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')) 
}); 
+0

更新的問題,因爲已經固定這個,但仍然不存儲this.ctx的值。 – Aly

+0

不會將數據添加到畫布jquery對象,而不是$(this)對象? – Aly

+0

它將添加到'canvas' jquery對象,但$(this)'將指向'down'方法中的相同畫布對象。 – ShankarSangoli