当我单击不同大小的表格按钮(如 3*3、5*5)时,我无法在 JavaScript 的同一页面中动态获取表格


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用于创建元素,如tabletrtdbutton
  • 简单文本的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);

最新更新