Javascript增量变量更新表格单元格onclick

时间:2012-09-20 08:14:55

标签: javascript html html-table onclick

我有一个用户输入颜色的页面,我调用onClick方法来更改表格各个单元格的颜色。但是,当我单击任何单元格时,只有最后一个单元格(在这种情况下为cell3)将改变颜色。我做错了什么?

我收到错误:

  

消息:'document.getElementById(...)'为null或不是对象
      行:24
      Char:4
      代码:0

我的代码是:

    <html>

    <body>
    <input type='text' id='userInput' value='yellow' />

    <table border="1"> 
        <tr>
            <td id="1">cell1
            </td>
        </tr>
        <tr>
            <td id="2">cell2
            </td>
        </tr>
        <tr>
            <td id="3">cell3
            </td>
        </tr>

    </table>

    <script type="text/javascript">
    for(var i = 1; i <= 3; i++){
        document.getElementById(i).onclick = function(){
        var newColor = document.getElementById('userInput').value;
            document.getElementById(i).style.backgroundColor = newColor;
        }
    }
    </script> 
    </body>

    </html>

3 个答案:

答案 0 :(得分:3)

将HTML更改为:ID必须以字母字符开头。以数字开头无效。

<table border="1"> 
    <tr>
        <td id="td1">cell1
        </td>
    </tr>
    <tr>
        <td id="td2">cell2
        </td>
    </tr>
    <tr>
        <td id="td3">cell3
        </td>
    </tr>

</table>

这是一个非常常见的Javascript问题:所有代码在循环结束时共享i的值3。您可以使用另一个辅助函数来解决它:

function changeIt(i) {
  // This inner function now has its own private copy of 'i'
  return function() {
    var newColor = document.getElementById('userInput').value;
      document.getElementById("td" + i).style.backgroundColor = newColor;
  }
}

for(var i = 1; i <= 3; i++){
    document.getElementById(i).onclick = changeIt(i);
}

它也可以使用匿名函数编写,但这些函数更难阅读。

答案 1 :(得分:1)

首先,你的for循环是错误的。尝试:

for(var i = 1; i <= 3; i++) {
   //code
}

其次,不是每次在循环中检索元素,而是使用this

this.style.backgroundColor = document.getElementById('userInput').value;

答案 2 :(得分:1)

Jeremy的答案很接近但是仍然有一个问题就是在点击元素之前没有被调用,到那时i的值仍然是3。使用Jeremy对HTML的更新,正确的脚本可以写成......

function createChangeColorHandler(n) {
  return function() {
    var newColor = document.getElementById('userInput').value;
    document.getElementById("td" + n).style.backgroundColor = newColor;
  }
}

for(var i = 1; i <= 3; i++) {
  // We pass i to the function createChangeColorHandler by value
  // at the time of this pass of the loop rather than referencing 
  // the variable directly after the loop has finished
  document.getElementById(i).onclick = createChangeColorHandler(i);
}

作为匿名函数......

for(var i = 1; i <= 3; i++) {
  // We pass i to the function createChangeColorHandler by value
  // at the time of this pass of the loop rather than referencing 
  // the variable directly after the loop has finished
  document.getElementById(i).onclick = (function(n) {
    return function() {
      var newColor = document.getElementById('userInput').value;
      document.getElementById("td" + n).style.backgroundColor = newColor;
    }
  })(i);
}

编辑杰里米的回答现在正确