ont*_*ia_ 3 html javascript dom html-table
注意:这是一个社区维基帖
使用简单dom方法的以下代码无法向表中添加行.有什么问题?
<html>
<head>
<title>Javascript Test</title>
<script>
function addRow() {
var mytable = document.getElementById('mytable');
var row = document.createElement('tr');
var cell = document.createElement('td');
var text = document.createTextNode('This is a row');
cell.appendChild(text);
row.appendChild(cell);
mytable.appendChild(row);
}
</script>
</head>
<body>
<form action="#">
<table id="mytable">
<tr>
<td>This is a row</td>
</tr>
</table>
<input type="button" onclick="addRow()" value="Add A Row"/>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这里的问题是<table>元素的正确结构不存在.处理表时,基本结构是:
<table>
<thead>
<tr>
<th>Heading for the table</th>
</tr>
</thead>
<tbody>
<tr>
<td>A row of data</td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
逻辑是,在处理表时,您希望保留列的标签,并将实际数据分开.因为大多数浏览器<tbody>都是在修复损坏的HTML的过程中填写的,所以很少有人意识到这一点.当浏览器看到您添加a时<tr>,它不知道您是否正在尝试将其添加到<thead>或<tbody>,因此它会失败.
以下显示了添加行的正确方法:
<html>
<head>
<title>Javascript Test</title>
<script>
function addRow() {
var mytbody = document.getElementById('mytbody');
var row = document.createElement('tr');
var cell = document.createElement('td');
var text = document.createTextNode('This is a row');
cell.appendChild(text);
row.appendChild(cell);
mytbody.appendChild(row);
}
</script>
</head>
<body>
<form action="#">
<table id="mytable">
<tbody id="mytbody">
<tr>
<td>This is a row</td>
</tr>
</tbody>
</table>
<input type="button" onclick="addRow()" value="Add A Row"/>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)