【问题标题】:Javascript error: function is not defined at HTMLTableCellElement.onclickJavascript 错误:函数未在 HTMLTableCellElement.onclick 中定义
【发布时间】:2017-11-08 03:08:40
【问题描述】:

所以我试图在 HTML/JS 上制作井字游戏,但是我的 onclicks 有点停止工作,我现在得到的错误是所有功能都没有定义。我尝试将 clear() 函数更改为 jQuery,但我无法对其进行测试。

Here is a jsfiddle.

本质上,它正在获取这个 html

 <td class="tile" id="pos1" onclick="draw(this); checkWinner();"></td>

识别这个javascript函数

var counter = 0;
function draw(elmt){
    if(elmt.innerHTML == "x" || elmt.innerHTML == "o")
    {
        //do nothing
    }
    else{
    if(counter==0){
        elmt.innerHTML = "x";
        counter = 1;
    }
    else{
        elmt.innerHTML = "o";
        counter = 0;
    }
    }
}

谢谢!

【问题讨论】:

  • Why does this simple JSFiddle not work? - JSFiddle 默认在事件发生后运行您提供的 JavaScript。这通常很有用,但会更改函数的范围,因此 on* 属性无法访问它们。您需要更改设置或绑定事件的方式。

标签: javascript jquery html onclick tic-tac-toe


【解决方案1】:

你的checkWinner函数没有定义,确保你所有的函数都定义在全局范围内,例如你必须可以访问window.draw()

最后,你也可以使用jQuery方便地绑定事件处理器,比如:

```

$('.tile').on('click', draw);

function draw(e) {
  var html = $(this).html();
  if(html == "x" || html == "o")
  {
    //do nothing
  } else{
    if(counter==0){
      $(this).html("x");
      counter = 1;
    }
    else{
      $(this).html("o");
      counter = 0;
    }
  }
}

```

var counter = 0;
function draw(elmt){
    if(elmt.innerHTML == "x" || elmt.innerHTML == "o")
    {
        //do nothing
    } else{
      if(counter==0){
          elmt.innerHTML = "x";
          counter = 1;
      }
      else{
          elmt.innerHTML = "o";
          counter = 0;
      }
    }
}
function checkWinner(){

}
<table>
<tr>
<td class="tile" id="pos1" onclick="draw(this); checkWinner();">
Click Here
</td>
</tr>
</table>

【讨论】:

    【解决方案2】:

    我猜他们的 jsfiddle 一定有问题你可以试试这个你的代码对我有用

    [just remove `$( document ).ready(function() {})`]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 2020-11-07
      • 2015-02-24
      • 1970-01-01
      • 2017-06-29
      • 1970-01-01
      相关资源
      最近更新 更多