0

我正在制作一个井字游戏,其中有一系列 9 个按钮。我根据 variable 的布尔值将背景图像更改为 anX或 an 。 OisX

我有div一个 id stage,其中包含 class 的所有按钮square。我在 上添加了一个侦听器stage并传递了一个event参数。但是,clickHandler无法识别该功能。铬 说:

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;
            }
        }
  }
4

1 回答 1

4

代码中有一些语法和语义错误——可能比我发现的要多,但它处于工作状态。

  1. 您只关闭forprepareBoard. 这导致clickHandler被定义为inside prepareBoard而不是 on window
  2. addEventListener,不是addEventHandler

http://jsfiddle.net/4pgQ8/

于 2013-04-25T03:45:05.563 回答