我是JavaScript的初学者,我想使用.innerHTML
从我的表中打印一些文本,但它不起作用。这是代码:
<table style="width:100%">
<tr>
<td id="tr"> </td>
<td id="tr1"> </td>
<td id="tr2"> </td>
</tr>
<tr>
<td id="tr3"> </td>
<td id="tr4"> </td>
<td id="tr5"> </td>
</tr>
<tr>
<td id="tr6"> </td>
<td id="tr7"> </td>
<td id="tr8"> </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>
答案 0 :(得分:1)
你错过了tr6,并且tr9不存在。 Here is a link to a working snapshot of your code。
但是,我建议你查看循环是如何工作的。
答案 1 :(得分:1)
此演示使用for
循环迭代<td>
的NodeList,并为每个<td>
分配一个字符串。
读:
// 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];
}
&#13;
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;
}
&#13;
<table style="width:100%">
<tr>
<td id="tr0"> </td>
<td id="tr1"> </td>
<td id="tr2"> </td>
</tr>
<tr>
<td id="tr3"> </td>
<td id="tr4"> </td>
<td id="tr5"> </td>
</tr>
<tr>
<td id="tr6"> </td>
<td id="tr7"> </td>
<td id="tr8"> </td>
</tr>
</table>
&#13;