使用 Javascript 创建表

Posted

技术标签:

【中文标题】使用 Javascript 创建表【英文标题】:Create table using Javascript 【发布时间】:2013-01-16 14:34:15 【问题描述】:

我有一个 javascript 函数,它创建一个包含 3 行 2 个单元格的表格。

谁能告诉我如何使用我的函数创建下表(我需要根据我的情况这样做)?

下面是我的 javascript 和 html 代码:

function tableCreate() 
  //body reference 
  var body = document.getElementsByTagName("body")[0];

  // create elements <table> and a <tbody>
  var tbl = document.createElement("table");
  var tblBody = document.createElement("tbody");

  // cells creation
  for (var j = 0; j <= 2; j++) 
    // table row creation
    var row = document.createElement("tr");

    for (var i = 0; i < 2; i++) 
      // create element <td> and text node 
      //Make text node the contents of <td> element
      // put <td> at end of the table row
      var cell = document.createElement("td");
      var cellText = document.createTextNode("cell is row " + j + ", column " + i);

      cell.appendChild(cellText);
      row.appendChild(cell);
    

    //row added to end of table body
    tblBody.appendChild(row);
  

  // append the <tbody> inside the <table>
  tbl.appendChild(tblBody);
  // put <table> in the <body>
  body.appendChild(tbl);
  // tbl border attribute to 
  tbl.setAttribute("border", "2");
<table  border="1">
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td rowspan="2">&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
</table>

【问题讨论】:

【参考方案1】:

使用insertRowinsertCell 的代码略短:

function tableCreate() 
  const body = document.body,
        tbl = document.createElement('table');
  tbl.style.width = '100px';
  tbl.style.border = '1px solid black';

  for (let i = 0; i < 3; i++) 
    const tr = tbl.insertRow();
    for (let j = 0; j < 2; j++) 
      if (i === 2 && j === 1) 
        break;
       else 
        const td = tr.insertCell();
        td.appendChild(document.createTextNode(`Cell I$i/J$j`));
        td.style.border = '1px solid black';
        if (i === 1 && j === 1) 
          td.setAttribute('rowSpan', '2');
        
      
    
  
  body.appendChild(tbl);


tableCreate();

此外,这并没有使用一些“坏习惯”,例如设置border属性而不是使用CSS,它通过document.body访问body而不是document.getElementsByTagName('body')[0]

【讨论】:

【参考方案2】:

当您想要动态的行和列时,此解决方案将是完美的。您可以接受行和列作为参数。

function tableCreate(row, col)
    let body = document.body;
    let tbl  = document.createElement('table');
    tbl.style.width  = '200px';
    tbl.style.border = '1px solid black';

    for(let i = 0; i < row; i++)
        let tr = tbl.insertRow();
        for(let j = 0; j < col; j++)
                let td = tr.insertCell();
                td.appendChild(document.createTextNode(`$i,$j` ));
                td.style.border = '1px solid black';
                 
    
    body.appendChild(tbl);


tableCreate(4,4);

输出 -

【讨论】:

【参考方案3】:

这是在javascript中使用.map函数的最新方法。

简单的表格代码..

    <table class="table table-hover">
        <thead class="thead-dark">
            <tr>
             <th scope="col">Tour</th>
             <th scope="col">Day</th>
             <th scope="col">Time</th>
             <th scope="col">Highlights</th>
             <th scope="col">Action</th>
           </tr>
        </thead>
      <tbody id="tableBody">
                                
 </tbody>
</table>

这里是在表格正文中附加一些内容的 javascript 代码。

    const data = "some kind of json data or object of arrays"; // ["Name:"Ali", "Day":"Monday"]
                const tableData = data.map(function(value)
                    return (
                        `<tr>
                            <td>$value.Name</td>
                            <td>$value.Day</td>
                            <td>$value.Time</td>
                            <td>$value.Highlights</td>
                            <td class="text-center"><a class="btn btn-primary" href="route.html?id=$value.ID" role="button">Details</a></td>
                        </tr>`
                    );
                ).join('');
            const tabelBody = document.querySelector("#tableBody");
                tableBody.innerHTML = tableData;

【讨论】:

【参考方案4】:

function creatTable(row = 10, col = 6) 
  var table = "<table style ='margin-left: auto;margin-right: auto; border-collapse: collapse; width: 70%; ' >";
  document.write(table);

  for (var h = 1; h < parseInt(col); h++) 

    th = "<th style='border: 3px solid #ddd;padding: 8px; padding-top: 12px;padding-bottom: 12px;text-align: center;background-color: #f5cf78;color: white;'>" + "I\'m Header";
    document.write(th);

    th += "</th>";

  

  for (var i = 1; i < parseInt(row); i++) 

    tr = "<tr style='background: ; :hoverbackground: #ffff99'>";
    document.write(tr);

    tr += "</tr>";

    for (var j = 1; j < parseInt(col); j++) 

      td = "<td style='border: 3px solid #ddd; padding: 8px;'>" + "I\'m cell no." + i + "," + j;
      document.write(td);

      td += "</td>";

    

    tr += "</tr>";
  

  table = "</table>";



console.log(creatTable())
<!DOCTYPE html>
<html>

<head>
  <title>JavaScript</title>
</head>

<body>

  <h1>JavaScript...</h1>
  <h2>Hello!</h2>
  <h3>This Table Created by JavaScript &copy;
    <font color=# ff0026>Geologist / Mohamed Yasser</font>
  </h3>




  <script src="main.js"></script>

</body>

</html>

【讨论】:

【参考方案5】:

你可能会觉得这很有帮助

<html>
 <head>
  <title>tABLE IN JS</title>
 </head>

 <body>
  <table border = "1">
     <tr>
        <th>Plug-in Name</th>
        <th>Filename</th>
        <th>Description</th>
     </tr>
     
     <script language = "JavaScript" type = "text/javascript">
        for (i = 0; i<3; i++) 
           document.write("<tr><td>");
           document.write("Hello world");
           document.write("</td><td>");
           document.write("Hello China");
           document.write("</td><td>");
           document.write("Hello USA");
           document.write("</td></tr>");
        
     </script>
  </table>      
 </body>
</html>

所以你根据你想要的列数创建表头,行将取决于你在迭代中指定的数字.....即这个将是 3。

【讨论】:

【参考方案6】:

这是一个使用 raphael.js 绘制表格的示例。 我们可以使用 Raphael.js 将表格直接绘制到浏览器的画布上 Raphael.js 是一个专为艺术家和平面设计师设计的 JavaScript 库。

<!DOCTYPE html>
<html>

    <head>
    </head>
    <body>
        <div id='panel'></div>
    </body>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"> </script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>    
paper = new Raphael(0,0,500,500);// width:500px, height:500px

var x = 100;
var y = 50;
var height = 50
var width = 100;

WriteTableRow(x,y,width*2,height,paper,"TOP Title");// draw a table header as merged cell
y= y+height;
WriteTableRow(x,y,width,height,paper,"Score,Player");// draw table header as individual cells
y= y+height;
for (i=1;i<=4;i++)

var k;
k = Math.floor(Math.random() * (10 + 1 - 5) + 5);//prepare table contents as random data
WriteTableRow(x,y,width,height,paper,i+","+ k + "");// draw a row
y= y+height;



function WriteTableRow(x,y,width,height,paper,TDdata)
 // width:cell width, height:cell height, paper: canvas, TDdata: texts for a row. Separated each cell content with a comma.

    var TD = TDdata.split(",");
    for (j=0;j<TD.length;j++)
    
        var rect = paper.rect(x,y,width,height).attr("fill":"white","stroke":"red");// draw outline
        paper.text(x+width/2, y+height/2, TD[j]) ;// draw cell text
        x = x + width;
    


</script>

</html>

请查看预览图:https://i.stack.imgur.com/RAFhH.png

【讨论】:

请在您的回答中添加一些解释!另外,不要忘记检查:How do I write a good answer? 我已经为代码添加了详细的解释。【参考方案7】:

var div = document.createElement('div');
            div.setAttribute("id", "tbl");
            document.body.appendChild(div)
                document.getElementById("tbl").innerHTML = "<table border = '1'>" +
              '<tr>' +
                '<th>Header 1</th>' +
                '<th>Header 2</th> ' +
                '<th>Header 3</th>' +
              '</tr>' +
              '<tr>' +
                '<td>Data 1</td>' +
                '<td>Data 2</td>' +
                '<td>Data 3</td>' +
              '</tr>' +
              '<tr>' +
                '<td>Data 1</td>' +
                '<td>Data 2</td>' +
                '<td>Data 3</td>' +
              '</tr>' +
              '<tr>' +
                '<td>Data 1</td>' +
                '<td>Data 2</td>' +
                '<td>Data 3</td>' +
              '</tr>' 

【讨论】:

【参考方案8】:

我编写了一个可以动态解析对象列表以将表创建为字符串的版本。我将其拆分为三个函数,用于编写标题列、正文行并将它们拼接在一起。我导出为字符串以在服务器上使用。我的代码使用template strings 来保持优雅。

如果您想添加样式(如引导程序),可以通过向 HEAD_PREFIXHEAD_SUFFIX 添加更多 html 来完成。

// helper functions
const TABLE_PREFIX = '<div><table class="tg">';
const TABLE_SUFFIX = '</table></div>';
const TABLE_HEAD_PREFIX = '<thead><tr>';
const TABLE_HEAD_SUFFIX = '</tr></thead>';
const TABLE_BODY_PREFIX = '<tbody><tr>';
const TABLE_BODY_SUFFIX = '</tr></tbody>';

function generateTableHead(cols) 
  return `
    $TABLE_HEAD_PREFIX
      <td>#</td>
    $cols.map((col) => `<td>$col</td>`).join('')
    $TABLE_HEAD_SUFFIX`;


function generateTableBody(cols, data) 
  return `
    $TABLE_BODY_PREFIX
    $data.map((object, index) => `
        <tr><td>$index</td>
        $cols.map((col) => `<td>$object[col]</td>`).join('')
      </tr>`).join('')
    $TABLE_BODY_SUFFIX`;


/**
 * generate an html table from an array of objects with the same values
 *
 * @param array<string> cols array of object columns used in order of columns on table
 * @param array<object> data array of objects containing data in a single depth
 */
function generateTable(data, defaultCols = false) 
  let cols = defaultCols;
  if (!cols) cols = Object.keys(data[0]); // auto generate columns if not defined
  return `
    $TABLE_PREFIX
    $generateTableHead(cols)
    $generateTableBody(cols, data)
    $TABLE_SUFFIX`;

这是一个使用示例:

const mountains = [
   height: 200, name: "Mt. Mountain" ,
   height: 323, name: "Old Broken Top",
]
const htmlTableString = generateTable(mountains );

【讨论】:

【参考方案9】:

var btn = document.createElement('button');
btn.innerHTML = "Create Table";
document.body.appendChild(btn);
btn.addEventListener("click", createTable, true);
function createTable()
var div = document.createElement('div');
div.setAttribute("id", "tbl");
document.body.appendChild(div)
	document.getElementById("tbl").innerHTML = "<table border = '1'>" +
  '<tr>' +
    '<th>Header 1</th>' +
    '<th>Header 2</th> ' +
    '<th>Header 3</th>' +
  '</tr>' +
  '<tr>' +
    '<td>Data 1</td>' +
    '<td>Data 2</td>' +
    '<td>Data 3</td>' +
  '</tr>' +
  '<tr>' +
    '<td>Data 1</td>' +
    '<td>Data 2</td>' +
    '<td>Data 3</td>' +
  '</tr>' +
  '<tr>' +
    '<td>Data 1</td>' +
    '<td>Data 2</td>' +
    '<td>Data 3</td>' +
  '</tr>' 
;

【讨论】:

这个答案可能是正确的,但原因并不明显。如果您也可以提供解释,这将对阅读您的答案的其他人更有用,并帮助他们确定它是否适用于他们的问题【参考方案10】:
<style>
    body
        background: radial-gradient(rgba(179,255,0.5),rgba(255,255,255,0.5),rgba(0,0,0,0.2));
        text-align: center;
    
    #name
        margin-top: 50px;
    
    .input
        font-size: 25px;
        color: #004d00;
        font-weight: 700;
        font-family: cursive;
    
    #entry
        width: 150px;
        height: 40px;
        font-size: 23px;
        font-family:  cursive;
        background-color: #001a66;
        color: whitesmoke;
        box-shadow: 0 2px 2px 0 rgba(0,0,0,0.5);
        margin: 20px;
    
    table
        border-collapse: collapse;
        width: 50%;
        margin: 50px auto;
        background-color: burlywood;
    
    table,th,td
       border: 2px solid black;
       padding:5px;

    
    th
        font-size: 30px;
        font-weight: 700;
        font-family: Arial;
        color: #004d00;
    
    td
        font-size: 25px;
        color: crimson;
        font-weight: 400;
        font-family: Georgia;
    
    .length
        width: 20%;
    
</style>
<body>
    <!-- Code to get student details -->
    <div id="container" >
        <div class="input">
             Name: <input type="text" id="name" class="length" placeholder="eg: Anil Ambani"/>
        </div>
        <div class="input">
             Email: <input type="text" id="mail" class="length" placeholder="eg: AnilAmbani@gmail.com"/>
        </div>
        <div class="input">
             Phone: <input type="text" id="phn"  class="length" placeholder="eg: 9898989898"/>
        </div>
        <div class="input">
             SLNO: <input type="number" id="sln" class="length" placeholder="eg: 1"/>
        </div>
        <br>
        <button id="entry"> I/P ENTRY</button>
    </div>
    <table id="tabledata">
       <tr>
          <th> Name</th>
          <th> Email</th>
          <th> Phone</th>
          <th> Slno</th>
       </tr> 
    </table>
</body>
<script>
    var entry = document.getElementById('entry');
    entry.addEventListener("click",display);
    var row = 1;
    function display()
        var nam =  document.getElementById('name').value;
        var emal = document.getElementById('mail').value;
        var ph = document.getElementById('phn').value;
        var sl = document.getElementById('sln').value;
        var disp = document.getElementById("tabledata");
        var newRow = disp.insertRow(row);
        var cell1 = newRow.insertCell(0);
        var cell2 = newRow.insertCell(1);
        var cell3 = newRow.insertCell(2);
        var cell4 = newRow.insertCell(3);
        cell1.innerHTML = nam;
        cell2.innerHTML = emal;
        cell3.innerHTML = ph;
        cell4.innerHTML = sl;
        row++;
    
</script>

【讨论】:

创建表单名称,然后创建一个函数给他们一个带有文档的新变量。id最初取行=1插入每个单元格及其索引位置,然后将对象分配给变量并增加行跨度> 【参考方案11】:

这是如何遍历一个 javascript 对象并将数据放入一个表中,代码修改自 @Vanuan 的答案。

<body>
    <script>
    function createTable(objectArray, fields, fieldTitles) 
      let body = document.getElementsByTagName('body')[0];
      let tbl = document.createElement('table');
      let thead = document.createElement('thead');
      let thr = document.createElement('tr');

      for (p in objectArray[0])
        let th = document.createElement('th');
        th.appendChild(document.createTextNode(p));
        thr.appendChild(th);
        
      
     
      thead.appendChild(thr);
      tbl.appendChild(thead);

      let tbdy = document.createElement('tbody');
      let tr = document.createElement('tr');
      objectArray.forEach((object) => 
        let n = 0;
        let tr = document.createElement('tr');
        for (p in objectArray[0])
          var td = document.createElement('td');
          td.setAttribute("style","border: 1px solid green");
          td.appendChild(document.createTextNode(object[p]));
          tr.appendChild(td);
          n++;
        ;
        tbdy.appendChild(tr);    
      );
      tbl.appendChild(tbdy);
      body.appendChild(tbl)
      return tbl;
    

    createTable([
                  name: 'Banana', price: '3.04', // k[0]
                  name: 'Orange', price: '2.56',  // k[1]
                  name: 'Apple', price: '1.45'
               ])
    </script>

【讨论】:

【参考方案12】:

function addTable() 
  var myTableDiv = document.getElementById("myDynamicTable");

  var table = document.createElement('TABLE');
  table.border = '1';

  var tableBody = document.createElement('TBODY');
  table.appendChild(tableBody);

  for (var i = 0; i < 3; i++) 
    var tr = document.createElement('TR');
    tableBody.appendChild(tr);

    for (var j = 0; j < 4; j++) 
      var td = document.createElement('TD');
      td.width = '75';
      td.appendChild(document.createTextNode("Cell " + i + "," + j));
      tr.appendChild(td);
    
  
  myTableDiv.appendChild(table);

addTable();
&lt;div id="myDynamicTable"&gt;&lt;/div&gt;

【讨论】:

【参考方案13】:

这应该可以工作(对上面的代码进行一些更改)。

function tableCreate() 
  var body = document.getElementsByTagName('body')[0];
  var tbl = document.createElement('table');
  tbl.style.width = '100%';
  tbl.setAttribute('border', '1');
  var tbdy = document.createElement('tbody');
  for (var i = 0; i < 3; i++) 
    var tr = document.createElement('tr');
    for (var j = 0; j < 2; j++) 
      if (i == 2 && j == 1) 
        break
       else 
        var td = document.createElement('td');
        td.appendChild(document.createTextNode('\u0020'))
        i == 1 && j == 1 ? td.setAttribute('rowSpan', '2') : null;
        tr.appendChild(td)
      
    
    tbdy.appendChild(tr);
  
  tbl.appendChild(tbdy);
  body.appendChild(tbl)

tableCreate();

【讨论】:

很好的解决方案,但最好在循环之外创建变量 @Cerbrus 这是一个很好的解决方案,但它在 IE8 之前不起作用。表已添加到 DOM Explorer,但不知何故,它是不可见的。有人知道怎么解决吗? @bdogru:为什么需要支持IE8?这是古老的。谷歌dropped that browser late 2012 @bdogru:那我建议你单独问一个问题。 @Cerbrus 我终于通过将最后一行更改为:body.innerHTML = tbl.outerHTML 解决了这个问题,它似乎 appendChild 更新 dom 结构但不重新渲染 html 视图(现代浏览器会)但 innerHTML 直接影响 html查看。【参考方案14】:

可能无法解决此特定问题中描述的问题,但可能对希望从对象数组创建表的人有用:

function createTable(objectArray, fields, fieldTitles) 
  let body = document.getElementsByTagName('body')[0];
  let tbl = document.createElement('table');
  let thead = document.createElement('thead');
  let thr = document.createElement('tr');
  fieldTitles.forEach((fieldTitle) => 
    let th = document.createElement('th');
    th.appendChild(document.createTextNode(fieldTitle));
    thr.appendChild(th);
  );
  thead.appendChild(thr);
  tbl.appendChild(thead);

  let tbdy = document.createElement('tbody');
  let tr = document.createElement('tr');
  objectArray.forEach((object) => 
    let tr = document.createElement('tr');
    fields.forEach((field) => 
      var td = document.createElement('td');
      td.appendChild(document.createTextNode(object[field]));
      tr.appendChild(td);
    );
    tbdy.appendChild(tr);    
  );
  tbl.appendChild(tbdy);
  body.appendChild(tbl)
  return tbl;


createTable([
  name: 'Banana', price: '3.04',
  name: 'Orange', price: '2.56',
  name: 'Apple', price: '1.45'
],
['name', 'price'], ['Name', 'Price']);

【讨论】:

【参考方案15】:

希望对您有所帮助。

HTML:

<html>
<head>
    <link rel = "stylesheet" href = "test.css">
<body>

</body>
<script src = "test.js"></script>
</head>
</html>

JAVASCRIPT:

var tableString = "<table>",
    body = document.getElementsByTagName('body')[0],
    div = document.createElement('div');

for (row = 1; row < 101; row += 1) 

    tableString += "<tr>";

    for (col = 1; col < 11; col += 1) 

        tableString += "<td>" + "row [" + row + "]" + "col [" + col + "]" + "</td>";
    
    tableString += "</tr>";


tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);

【讨论】:

【参考方案16】:
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Insert title here</title>
    </head>
    <body>
        <table id="myTable" cellpadding="2" cellspacing="2" border="1" onclick="tester()"></table>
        <script>
            var student;
            for (var j = 0; j < 10; j++) 
                student = 
                    name: "Name" + j,
                    rank: "Rank" + j,
                    stuclass: "Class" + j,
                ;
                var table = document.getElementById("myTable");
                var row = table.insertRow(j);
                var cell1 = row.insertCell(0);
                var cell2 = row.insertCell(1);
                var cell3 = row.insertCell(2);

                cell1.innerHTML = student.name,
                cell2.innerHTML = student.rank,
                cell3.innerHTML = student.stuclass;
            
        </script>
    </body>
</html>

【讨论】:

【参考方案17】:
<!DOCTYPE html>
<html>
    <body>
        <p id="p1">
            <b>Enter the no of row and column to create table:</b>
            <br/><br/>
            <table>
                <tr>
                    <th>No. of Row(s) </th>
                    <th>No. of Column(s)</th>
                </tr>
                <tr>
                    <td><input type="text" id="row" value="4" /> X</td>
                    <td><input type="text" id="col" value="7" />Y</td>
                </tr>
            </table>
            <br/>
            <button id="create" onclick="create()">create table</button>
        </p>
        <br/><br/>
        <input type="button" value="Reload page" onclick="reloadPage()">
        <script>
            function create() 
                var row = parseInt(document.getElementById("row").value);
                var col = parseInt(document.getElementById("col").value);

                var tablestart="<table id=myTable border=1>";
                var tableend = "</table>";
                var trstart = "<tr bgcolor=#ff9966>";
                var trend = "</tr>";
                var tdstart = "<td>";
                var tdend = "</td>";
                var data="data in cell";
                var str1=tablestart + trstart + tdstart + data + tdend + trend + tableend;
                document.write(tablestart);

                for (var r=0;r<row;r++) 
                    document.write(trstart);
                    for(var c=0; c<col; c++) 
                        document.write(tdstart+"Row."+r+" Col."+c+tdend);
                    
                

                document.write(tableend);
                document.write("<br/>");
                var s="<button id="+"delete"+" onclick="+"deleteTable()"+">Delete top Row </button>";
                document.write(s);
                var relod="<button id="+"relod"+" onclick="+"reloadPage()"+">Reload Page </button>";
                document.write(relod);
            
            function deleteTable() 
                var dr=0;
                if(confirm("It will be deleted..!!")) 
                    document.getElementById("myTable").deleteRow(dr);
                
            
            function reloadPage()
                location.reload();
            
        </script>
    </body>
</html>

【讨论】:

以上是关于使用 Javascript 创建表的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript忍者阅读随笔:函数声明调用

更改 URL 的一部分以在 JavaScript 中显示不同的数据

JavaScript高级程序设计笔记之面向对象

使用 Javascript 创建表

使用JavaScript

JavaScript面向对象