如何更改点击按钮的值?

时间:2016-02-28 07:19:15

标签: javascript html

这是我的代码.Id正在通过。但是无法更改值。它显示null的变化值。我需要将其值更改为" X"的onclick。

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="tictactoe.css" />
</head>
<body>
   <table cellpadding="0" cellspacing="0">
       <tr>
          <td><input type="button" value=" " class="buttons" id="1" onclick="tictactoe(this.id)"></td>
          <td><input type="button" value=" " class="buttons" id="2" onclick="tictactoe(this.id)"></td>
          <td><input type="button" value=" " class="buttons" id="3" onclick="tictactoe(this.id)"></td>
       </tr>
       <tr>
          <td><input type="button" value=" " class="buttons" id="4" onclick="tictactoe(this.id)"></td>
          <td><input type="button" value=" " class="buttons" id="5" onclick="tictactoe(this.id)"></td>
          <td><input type="button" value=" " class="buttons" id="6" onclick="tictactoe(this.id)"></td>
       </tr>
       <tr>
          <td><input type="button" value=" " class="buttons" id="7" onclick="tictactoe(this.id)"></td>
          <td><input type="button" value=" " class="buttons" id="8" onclick="tictactoe(this.id)"></td>
          <td><input type="button" value=" " class="buttons" id="9" onclick="tictactoe(this.id)"></td>
       </tr>
    </table>
</body>
<script type="text/javascript">
    tictactoe = function(id) {
    var box = document.getElementById("this.id");
    box.value = "X";
    }
</script>
</html>

2 个答案:

答案 0 :(得分:1)

试试这个,希望能有效

<script type="text/javascript">
tictactoe = function(id) {
var box = document.getElementById(id);
box.value = "X";
}

工作示例here

答案 1 :(得分:0)

将onclick侦听器保留在HTML本身上通常不是一种好习惯。

此外,请确保您的ID以字母开头。

您正在寻找的解决方案可以按如下方式进行:

HTML:

<table cellpadding="0" cellspacing="0">
    <tr>
       <td><input type="button" value=" " class="buttons" id="b1"></td>
       <td><input type="button" value=" " class="buttons" id="b2"></td>
       <td><input type="button" value=" " class="buttons" id="b3"></td>
    </tr>
    <tr>
       <td><input type="button" value=" " class="buttons" id="b4"></td>
       <td><input type="button" value=" " class="buttons" id="b5"></td>
       <td><input type="button" value=" " class="buttons" id="b6"></td>
    </tr>
    <tr>
       <td><input type="button" value=" " class="buttons" id="b7"></td>
       <td><input type="button" value=" " class="buttons" id="b8"></td>
       <td><input type="button" value=" " class="buttons" id="b9"></td>
    </tr>
 </table>

和js:

    var setButtonListener = function (i) {
      document.getElementById('b' + i).addEventListener('click', function (e) {
        var current = i;
        e.target.setAttribute('value', current);
      });
    };
    var i;
    for (i = 1; i < 10; i++) {
      setButtonListener(i);
    }

Demo