使用香草 JS 和循环绘制表格

Drawing a table with vanilla JS and loops

本文关键字:循环 绘制 表格 JS 香草      更新时间:2023-09-26

我正在做一个练习(从开始Javascript)来更好地理解DOM操作。尝试仅使用 JS 在 DRY 方法中重新创建下表(教科书解决方案在这里):

<table>
    <tr>
        <td>Car</td>
        <td>Top Speed</td>
        <td>Price</td>
    </tr>
    <tr>
        <td>Chevrolet</td>
        <td>120mph</td>
        <td>$10,000</td>
   </tr>
   <tr>
       <td>Pontiac</td>
       <td>140mph</td>
       <td>$20,000</td>
   </tr>
</table>

我试过这个,但不确定如何在不抛出错误的情况下循环创建变量:

var array = [['Car', 'Top Speed', 'Price'],['Chevrolet', '120mph', '$10,000'], ['Pontiac', '140pmh', '$20,000']] // Creating a data array which a loop will source from
    var table = document.createElement('table');
    document.body.appendChild(table); // Drew the main table node on the document
    for (var i = 0; i<3; i++) { 
        var tr[i] = document.createElement('tr'); //Create 3 <tr> elements assigned to a unique variable BUT need a working alternative for 'tr[i]'
        table.appendChild(tr[i]); // Append to <table> node
        for (var j = 0; j<3; j++) {
            var tdText = document.createTextNode(array[i][j]); // Extract data from array to a placeholder variable
            tr[i].appendChild(tdText); // Take string from placeholder variable and append it to <tr> node
        }
    }

如前所述,问题是声明tr[i]变量时的语法错误。

更干净的方法是使用表 api 方法,例如

var array = [
    ['Car', 'Top Speed', 'Price'],
    ['Chevrolet', '120mph', '$10,000'],
    ['Pontiac', '140pmh', '$20,000']
  ] // Creating a data array which a loop will source from
var table = document.createElement('table');
document.body.appendChild(table); // Drew the main table node on the document
array.forEach(function(row) {
  var tr = table.insertRow(); //Create a new row
  row.forEach(function(column) {
    var td = tr.insertCell();
    td.innerText = column; // Take string from placeholder variable and append it to <tr> node
  });
});

  • HTMLTableElement
  • 插入行()
  • 插入单元格

请使用 tr 而不是 tr[i] 。它会工作

var array = [['Car', 'Top Speed', 'Price'],['Chevrolet', '120mph', '$10,000'], ['Pontiac', '140pmh', '$20,000']] // Creating a data array which a loop will source from
    var table = document.createElement('table');
    document.body.appendChild(table); // Drew the main table node on the document
    for (var i = 0; i<3; i++) { 
        var tr = document.createElement('tr'); //Create 3 <tr> elements assigned to a unique variable BUT need a working alternative for 'tr[i]'
        table.appendChild(tr); // Append to <table> node
        for (var j = 0; j<3; j++) {
            var tdElement = document.createElement('td');
            tdElement.innerHTML = array[i][j];
            tr.appendChild(tdElement); // Take string from placeholder variable and append it to <tr> node
        }
    }

我的版本使用THeadTBody以及thtd

// input as an array
const array = [
  ['Car', 'Top Speed', 'Price'],
  ['Chevrolet', '120mph', '$10,000'],
  ['Pontiac', '140pmh', '$20,000']
]
const table = document.createElement('table');
// Generate Header
const head = table.createTHead();
const tr = head.insertRow();
array[0].forEach(function(item) {
  const th = document.createElement('th')
  th.appendChild(document.createTextNode(item));
  tr.appendChild(th);
});
// Generate Body
const body = table.createTBody();
array.slice(1).forEach(function(row) {
  const tr = body.insertRow();
  row.forEach(function(item, index) {
    if (index === 0) {
      const th = document.createElement('th')
      th.appendChild(document.createTextNode(item));
      tr.appendChild(th);
    } else {
      const td = tr.insertCell(); // create td only
      td.appendChild(document.createTextNode(item));
    }
  });
});
document.body.appendChild(table);

裁判:

  • <thead> : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead
  • <tbody> : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody
  • <th> : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th