function boardSize() {
var rows = 3;
var cols = 3;
document.write(" <table> ");
for (i = 0; i < rows; i++) {
document.write("<tr>");
for (j = 0; j < cols; j++) {
var btncolo;
var btnarr = ["red", "blue", "yellow"];
var x = Math.floor((Math.random() * 3) + 1);
btncolo = btnarr[x - 1];
var stringArray = ["<td><input type='button' style=backgroundcolor:'", btncolo, "' onclick='hitheadr('id')'> </td>"];
document.write(stringArray.join(""));
}
document.write("</tr>");
}
document.write(" </table>");
}
我一直在尝试用它在同一页面中显示表格,但我无法得到结果。
我知道我使用 document.write()
的原因是在其他页面中给出结果。
我可以使用什么来获得所需的结果?
最佳答案
您可以创建 DOM 元素并将其附加到正文,而不是将其写入文档(可能是在加载页面之后),这会导致奇怪的结果。
一些有用的方法:
-
document.createElement
用于创建元素,例如table
、tr
、td
、button
-
document.createTextNode
对于简单的文本 -
Node.appendChild
这会将节点添加到父节点的末尾
function hitheadr(id) {
return function () {
console.log(id);
};
}
function createTable(rows, cols, element) {
function getButtonId(i, j) {
return 'button' + i + '|' + j
}
var table = document.createElement('table'),
tr, td, button, i, j,
colors = ["red", "blue", "yellow"];
for (i = 0; i < rows; i++) {
tr = document.createElement('tr');
for (j = 0; j < cols; j++) {
td = document.createElement('td');
button = document.createElement('button');
button.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
button.appendChild(document.createTextNode(getButtonId(i, j)));
button.onclick = hitheadr(getButtonId(i, j));
button.id = getButtonId(i, j);
td.appendChild(button);
tr.appendChild(td);
}
table.appendChild(tr);
}
element.appendChild(table);
}
createTable(3, 3, document.body);
关于javascript - 当我单击不同大小的表格按钮(如 3*3 ,5*5)时,我无法在 JavaScript 的同一页面中动态获取表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41957596/