2016-02-28 262 views
-1

這是我的code.Id正在通過。但不能改變value.Its顯示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> 
+0

var box = document.getElementById(passedArgument);'爲什麼引用...它將被視爲字符串... – Rayon

回答

1

試試這個,希望將工作

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

工作實例here

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