[英]How to call a function outside of javascript click event
在以下代碼下,如何在畫布單擊事件中調用函數searchBlock()
? this.searchBlock()
在這里不能工作!
Board.prototype = {
addHandlerToBlock:function(){
this.canvas.onclick = function(e){
var e = window.event || e;
var rect = this.getBoundingClientRect();
var mouseX = e.clientX - rect.left;
var mouseY = e.clientY - rect.top;
var clickBlockId = this.searchBlock(mouseX, mouseY) || -1;
if(clickBlockId >= 0){
if(canMove(this.puzzle[clickBlockId])){
alert("ha")
}
}
this.refresh(p);
}
},
searchBlock:function(x, y){
for(var i = 0; i < this.puzzle.length; i++){
if( x - this.puzzle[i].x > 0 && y - this.puzzle[i].y > 0){
return i;
}
}
}
}
嘗試這個。 不一定嚴格要this
變量加上別名,但我喜歡這樣做,因為可以在this
傳遞不同的值的同時調用該方法。
Board.prototype = {
addHandlerToBlock:function(){
var that = this; // alias to "this"
this.canvas.onclick = function(e){
...
var block = that.searchBlock(x, y);
}
},
searchBlock:function(x, y){
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.