2013-04-25 109 views
0

我正在製作一個井字遊戲,其中我有一系列9個按鈕。我根據變量isX的布爾值將背景圖像更改爲XO未識別JavaScript功能

我有一個div與編號stage它擁有類square的所有按鈕。我在stage上添加了一個監聽器,並通過了event參數。但是,功能clickHandler未被識別。 Chrome的說:

Uncaught ReferenceError: clickHandler is not defined 2Players.html:38 
(anonymous function) 

HTML:

<body> 
    <div id="stage"> 

    </div> 
</body> 

CSS:

#stage{ 
    width: 400px; 
    height: 400px; 
    padding: 0px; 
    position: relative; 
} 
.square{ 
    width: 64px; 
    height: 64px; 
    background-color: gray; 
    position: absolute; 
} 

的JavaScript:

 const ROWS = 3; 
     const COLS = 3; 
     const GAP = 10; 
     const SIZE = 64; 
     var stage = document.querySelector("#stage"); 
     var lotOfButtons = []; 

     var winningPatterns = ["123","159","147", 
           "258","357","369", 
           "456","789"]; 
     var isX = true; 
     var player1Pattern = ""; 
     var player2Pattern = ""; 

     stage.addEventHandler("click",clickHandler,false); 
     prepareBoard(); 

     function prepareBoard(){ 
      for(var row = 0;row<ROWS;row++){ 
      for(var col = 0;col < COLS;col++){ 
       var square = document.createElement("button"); 
       square.setAttribute("class","square"); 
       stage.appendChild(square); 
       lotOfButtons.push(square); 
       square.style.left = col * (SIZE+GAP) + "px"; 
       square.style.top = row * (SIZE+GAP) + "px"; 
      } 
     } 
     function clickHandler(event){ 
      if(isX===true){ 
       event.target.style.backgroundImage = "url(../img/X.PNG)"; 
       isX = false; 
      }else{ 
       event.target.style.backgroundImage = "url(../img/O.PNG)"; 
       isX = true; 
      } 
     } 
    } 
+1

拋開你的問題,你可能會受益於使用spritesheet,只是抵消背景位置,而不是交換圖像。 – 2013-04-25 03:44:41

+0

@KaiQing肯定的事情,會學到:) – 2013-04-25 04:08:14

回答

4

你必須在代碼中的一些語法和語義錯誤 - 可能比我抓到的更多,但它正在工作泰特。

  1. 你只在prepareBoard關閉嵌套循環for括號中的一個。這導致clickHandlerprepareBoard內被定義爲,而不是在window
  2. 這是addEventListener,而不是addEventHandler

http://jsfiddle.net/4pgQ8/

+0

哎呀!那是......我的愚蠢。 – 2013-04-25 03:46:08