Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何更改单击时按钮的值?_Javascript_Html - Fatal编程技术网

Javascript 如何更改单击时按钮的值?

Javascript 如何更改单击时按钮的值?,javascript,html,Javascript,Html,这是我的代码。Id正在通过。但无法更改值。它显示的值不能更改为null。我需要在单击时将其值更改为“X” tictactoe=功能(id){ var box=document.getElementById(“this.id”); box.value=“X”; } 将onclick侦听器保留在HTML本身上通常不是好的做法 此外,请确保您的ID以字母开头 您正在寻找的解决方案如下所示: HTML: <table cellpadding="0" cellspacing="0">

这是我的代码。Id正在通过。但无法更改值。它显示的值不能更改为null。我需要在单击时将其值更改为“X”


tictactoe=功能(id){
var box=document.getElementById(“this.id”);
box.value=“X”;
}

将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);
    }
var setButtonListener=函数(i){
document.getElementById('b'+i.).addEventListener('click',函数(e){
无功电流=i;
e、 target.setAttribute(“值”,当前);
});
};
var i;
对于(i=1;i<10;i++){
挫折监听器(一);
}

试试这个,希望能奏效

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

tictactoe=功能(id){
变量框=document.getElementById(id);
box.value=“X”;
}


工作示例。

var-box=document.getElementById(passedArgument)为什么加引号…将在字符串处处理。。。
<script type="text/javascript">
tictactoe = function(id) {
var box = document.getElementById(id);
box.value = "X";
}