如何使用Javascript和HTML DOM在表的特定单元格中显示数字

How can I display the numbers in specific cells of the table using Javascript and HTML DOM?

本文关键字:单元格 数字 显示 Javascript 何使用 HTML DOM      更新时间:2023-09-26

我解决了这个练习的一部分,从用户那里获取输入,onclick按钮,它会动态创建表格。行数等于输入,列数是从用户那里获取的输入的两倍。但是我不知道如何在这样的某些单元格内显示数字。

参考

function createTable() {
  var usrInput = document.getElementById('input').value;
  var theader = '<table border="1">'n';
  var tbody = '';
  for (var i = 0; i < usrInput; i++) {
    tbody += '<tr>';
    for (var j = 0; j < 2 * usrInput; j++) {
      tbody += '<td>';
      tbody += '1' + i + ',' + j;
      tbody += '</td>';
    }
    tbody += '</tr>';
  }
  var tfooter = '</table>';
  document.getElementById('layer').innerHTML = theader + tbody + tfooter;
}
<!Doctype html>
<html>
<body>
  <form>
    <input type="text" id="input" />
    <input type="button" value="Create Table" onclick='createTable()' />
    <br/>
  </form>
  <div id="layer"></div>
</html>

你可以尝试这样的事情:

逻辑:

在矩阵中,您必须映射对角线,因此如果行和列相同,则row + column === length-1一个。 -1因为,循环从0开始。第二个对角线将是row === column .

在您的情况下,第一个对角线仍然有效。 对于另一个,您可以尝试column - length === rowcolumn-row === length

function createTable() {
  var usrInput = document.getElementById('input').value;
  var theader = '<table border="1">'n';
  var tbody = '';
  for (var i = 0; i < usrInput; i++) {
    tbody += '<tr>';
    for (var j = 0; j < 2 * usrInput; j++) {
      tbody += '<td>';
      
      if(((i+j) === usrInput-1) ||((j-i) === parseInt(usrInput)))
        tbody += i+1;
      else{
        tbody += " ";
      }
      tbody += '</td>';
    }
    tbody += '</tr>';
  }
  var tfooter = '</table>';
  document.getElementById('layer').innerHTML = theader + tbody + tfooter;
}
td{
  width:20px;
  height:20px;
}
<!Doctype html>
<html>
<body>
  <form>
    <input type="text" id="input" />
    <input type="button" value="Create Table" onclick='createTable()' />
    <br/>
  </form>
  <div id="layer"></div>
</html>

你可以试试这个,这是另一种解决方案

function createTable() {
  var usrInput = document.getElementById('input').value;
  var theader = '<table border="1">'n';
  var tbody = '';
  for (var i = 0; i < usrInput; i++) {
    tbody += '<tr>';
    for (var j=usrInput;j>0;j--) {
        if (i == j-1) {
        tbody += '<td>';
      tbody += i+1 ;
      tbody += '</td>';
    } else {
    tbody += '<td>';
      tbody += "" ;
      tbody += '</td>';
    }
    }
    for (var j=0;j<usrInput;j++) {
        if (i == j) {
        tbody += '<td>';
      tbody += i+1 ;
      tbody += '</td>';
    } else {
    tbody += '<td>';
      tbody += "" ;
      tbody += '</td>';
    }
    }

    tbody += '</tr>';
  }