开发者问题收集

在 JavaScript 函数中分配函数参数以修改表格单元格时出错

2022-04-24
91

我尝试运行以下代码时出现以下两个错误:

Uncaught TypeError: Cannot read properties of null (reading 'rows') at changeContent

Uncaught TypeError: Cannot read properties of null (reading 'rows') at changeContent

function changeContent(r, c, con) {
    var row = document.getElementById('myTable').rows[r].cells;
    row[c].innerHTML =con;
}

changeContent(0, 0, "changed");
<!DOCTYPE html>
<html><head><meta charset=utf-8 />
<title>Change the content of a cell</title>
<script src="index.js"></script>
</head><body>
<table id="myTable" border="1">
<tr><td>Row1 cell1</td>
<td>Row1 cell2</td></tr>
<tr><td>Row2 cell1</td>
<td>Row2 cell2</td></tr>
<tr><td>Row3 cell1</td>
<td>Row3 cell2</td></tr>
</table><form>
<input type="button" onclick="changeContent()" value="Change content">
</form></body></html>

我该如何纠正?谢谢。

编辑:我终于找到了一些可行的方法:

function changeContent(r=0, c=1, con="changed") {
var row = document.getElementById('myTable').rows[r].cells;
row[c].innerHTML =con;

2个回答

您可以尝试以您想要/需要一些用户输入的方式执行此操作。因此,它只能根据这一点进行更改,除此之外,您还必须提供一些数据:

function changeContent()
{
rn = window.prompt("Input the Row number(0,1,2)", "0");
cn = window.prompt("Input the Column number(0,1)","0");
content = window.prompt("Input the Cell content");  
var x=document.getElementById('myTable').rows[parseInt(rn,10)].cells;
x[parseInt(cn,10)].innerHTML=content;
}
<html> 
<head> 
<meta charset=utf-8 /> 
<title>Change the content of a cell</title> 
<style type="text/css"> 
body {margin: 30px;} 
</style>  
</head><body> 
<table id="myTable" border="1"> 
<tr><td>Row1 cell1</td> 
<td>Row1 cell2</td></tr> 
<tr><td>Row2 cell1</td> 
<td>Row2 cell2</td></tr> 
<tr><td>Row3 cell1</td> 
<td>Row3 cell2</td></tr> 
</table><form> 
<input type="button" onclick="changeContent()" value="Change content"> 
</form></body></html>
ash
2022-04-24

终于找到解决办法了,我直接给函数参数赋值了:

function changeContent(r=0, c=1, con="changed") {
    var row = document.getElementById('myTable').rows[r].cells;
    row[c].innerHTML =con;
}
scisamir
2022-04-25