假设我有这三个空格,一开始就是空白的。我想在 JavaScript 中使用innerHTML 进行更改。
<p id="topname"></p>
<div id="table"></div>
<p id="botname"></p>
document.getElementById("topname").innerHTML = "Boy";
document.getElementById("botname").innerHTML = "Girl";
我设法使用innerHTML更改了topname和botname。如何更改 div id="table" 以显示 x x y(2x2、4x4、8x8 等)表格?
最佳答案
而不是替换 <div>
与 <table>
,建议创建<table>
作为 <div>
的子节点只要您没有向 <div>
添加额外的样式即可(如填充或边距),这不会对显示产生影响。
需要构建几个循环 <tr>
和<td>
会做这项工作。这是一个接受 x 和 y 的函数:
function makeTable(rows, cols) {
// Create a table node
var tbl = document.createElement('table');
// Make a <tr> for each row
for (var i=0; i<rows; i++) {
var tr = document.createElement('tr');
// And make a <td> for eah col
for (var j=0; j<cols; j++) {
var td = document.createElement('td');
// Append them to the current tr
tr.appendChild(td);
}
// Append the row
tbl.appendChild(tr);
}
return tbl;
}
// Create a new 2x4 table with the function
var newTable = makeTable(2, 4);
// And append it as a child to the <div id='table'>
document.getElementById('table').appendChild(newTable);
Here it is in action
关于javascript - 使用表格更改 div 空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13232003/