小编典典

使用Javascript创建表格

javascript

我有一个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 width="100%" 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>

阅读 383

收藏
2020-05-01

共1个答案

小编典典

这应该起作用(对上面的代码进行一些改动)。

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();
2020-05-01