首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法使用innerHTML通过JavaScript更新HTML表

无法使用innerHTML通过JavaScript更新HTML表
EN

Stack Overflow用户
提问于 2016-03-20 04:40:06
回答 2查看 97关注 0票数 0

我是JavaScript的初学者,我想用.innerHTML从我的表格中打印一些文本,但它不起作用。代码如下:

代码语言:javascript
运行
复制
<table style="width:100%">
    <tr>
        <td id="tr">&nbsp;</td>
        <td id="tr1">&nbsp;</td>
        <td id="tr2">&nbsp;</td>
    </tr>
    <tr>
       <td id="tr3">&nbsp;</td>
       <td id="tr4">&nbsp;</td>
       <td id="tr5">&nbsp;</td>
    </tr>
    <tr>
       <td id="tr6">&nbsp;</td>
       <td id="tr7">&nbsp;</td>
       <td id="tr8">&nbsp;</td>
    </tr>
</table>

<script>
document.getElementById("tr").innerHTML = "some text";
document.getElementById("tr2").innerHTML = "some text1";
document.getElementById("tr2").innerHTML = "some text2";
document.getElementById("tr3").innerHTML = "some text3";
document.getElementById("tr4").innerHTML = "some text4";
document.getElementById("tr5").innerHTML = "some text5";
document.getElementById("tr7").innerHTML = "some text6";
document.getElementById("tr8").innerHTML = "some text7";
document.getElementById("tr9").innerHTML = "some text8";
</script>
EN

回答 2

Stack Overflow用户

发布于 2016-03-20 04:47:48

你错过了tr6,而tr9并不存在。Here is a link to a working snapshot of your code

但是,我建议您查看循环是如何工作的。

票数 1
EN

Stack Overflow用户

发布于 2016-03-20 08:25:28

此演示使用for循环遍历<td>的NodeList,并为每个<td>分配一个字符串。

阅读:

代码语言:javascript
运行
复制
// Create an array of strings.
// Each string represents what will be in each cell
var content = ['row 1 col 1', 'row 1 col 2', 'row 1 col 3', 'row 2 col 1', 'row 2 col 2', 'row 2 col 3', 'row 3 col 1', 'row 3 col 2', 'row 3 col 3'];

// Create a NodeList of every <td> with querySelectorAll()
var cells = document.querySelectorAll('td');

//Iterate through the Nodelist (cells[]) and assign a string from the array (content[])
for (var i = 0; i < cells.length; i++) {
  cells[i].innerHTML = content[i];
}
代码语言:javascript
运行
复制
table {
  border: 3px solid grey;
  table-layout: fixed;
  margin: 40px auto;
}
td {
  border: 3px inset black;
  outline: 2px outset grey;
  height: 30px;
  width: 30px;
  color: blue;
  padding: 5px;
}
代码语言:javascript
运行
复制
<table style="width:100%">
  <tr>
    <td id="tr0">&nbsp;</td>
    <td id="tr1">&nbsp;</td>
    <td id="tr2">&nbsp;</td>
  </tr>
  <tr>
    <td id="tr3">&nbsp;</td>
    <td id="tr4">&nbsp;</td>
    <td id="tr5">&nbsp;</td>
  </tr>
  <tr>
    <td id="tr6">&nbsp;</td>
    <td id="tr7">&nbsp;</td>
    <td id="tr8">&nbsp;</td>
  </tr>
</table>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36106870

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档