0

所以我有推多維數組值像這樣的參數的javascript函數:開關手柄多維陣列。意想不到的結果

function mouseHandle(x,y){ 
    for(var i=0; i<buttonPos.length; i++){ 
     if(x>buttonPos[i][0] && x<buttonPos[i][2]){ 
      if(y>buttonPos[i][1] && y<buttonPos[i][3]){ 
       eventButton(buttonPos[i][4]); 
      }; 
     }; 
    }; 
}; 

此推buttonPos [I] [4]至eventButton函數,它是:

function eventButton(d){ 
    switch(d){ 
     case 0: // STARTBUTTON 
      alert("Button"); 
      break; 
     default: 
      alert("NoButton"); 
    }; 
}; 

陣列被設置在drawButton功能像這樣:

function drawButton(x,y,width,height,string,event){ 
    xCenterButton=x+(width/2); 
    yCenterButton=y+(height/2); 

    ctx.fillStyle="rgba(242,255,195,1)"; 
    ctx.fillRect(x,y,width,height); 

    ctx.rect(x,y,width,height); 
    ctx.fillStyle="rgba(0,0,0,1)"; 
    ctx.stroke(); 

    ctx.font="25px Arial"; 

    fontSize = getFontSize(); 
    centerNum = fontSize/4; 

    ctx.fillStyle="rgba(0,0,0,1)"; 
    ctx.textAlign="center"; 
    ctx.fillText(string,xCenterButton,yCenterButton+centerNum); 

    buttonPos.push([[x],[y],[x+width],[y+height],[event]]); 
}; 

我然後調用在menuStart功能的功能,以便:

function menuStart(){ 
    drawButton(getCenterX(100),getCenterY(50),100,50,"Start",0); 
}; 

所以mouseHandle功能DOES得到eventButton正常操作(I提醒的默認情況中的「d」參數)的0的參數。但是,就好像switch語句不能識別0,因爲它使用默認情況併發出「NoButton」警報。

任何想法,爲什麼這不工作?

注 - 根據請求提供JSFIDDLE。 :: http://jsfiddle.net/jWFwX/

+1

嘗試'情況 '0':'。你很可能傳入一個字符串而不是一個整數。 – Andy

+0

@Andy - 仍然給我默認情況。 –

+0

@Andy我會嘗試改變它,看看傳遞一個字符串是否有所作爲。 –

回答

1

將d解析爲int並首先將其解析。工作JSFiddle

新代碼:

function eventButton(d){ 
    var buttonInt = parseInt(d); 
    switch(buttonInt){ 
    case 0: // STARTBUTTON 
     alert("Button"); 
     break; 
    default: 
     alert("NoButton"); 
     alert(d); 
    }; 
}; 
+0

該解決方案有效,但我想使用switch語句,因爲我會有很多事件。我想我必須做:(謝謝! –

+1

這是一個更好的解決方案,它使用開關,但首先將d轉換爲int:http://jsfiddle.net/jWFwX/13/ – guymid

+0

究竟是我需要。Perfecto!謝謝! –