我有一个页面,用户可以在其中输入颜色,然后我调用 onClick 方法来更改表格中各个单元格的颜色。但是,当我单击任何单元格时,只有最后一个单元格(在本例中为 cell3)会改变颜色。我做错了什么?
我得到错误:
Message: 'document.getElementById(...)' is null or not an object
Line: 24
Char: 4
Code: 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>
最佳答案
将您的 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);
}
它也可以使用匿名函数来编写,但是那些更难阅读。
关于Javascript增量变量来更新表格单元格onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12508563/