web-dev-qa-db-ja.com

Javascriptを使ってテーブルを作成する

3行2セルのテーブルを作成するJavaScript関数があります。

自分の関数を使用して以下の表を作成する方法を誰かに教えてもらえますか(私の状況ではこれを実行する必要があります)。

これが私の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>
80

これはうまくいくはずです(上記のコードに対するいくつかの変更から)。

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();
91
Craig Taub

insertRow および insertCell を使用した少し短いコード

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

    for(var i = 0; i < 3; i++){
        var tr = tbl.insertRow();
        for(var j = 0; j < 2; j++){
            if(i == 2 && j == 1){
                break;
            } else {
                var td = tr.insertCell();
                td.appendChild(document.createTextNode('Cell'));
                td.style.border = '1px solid black';
                if(i == 1 && j == 1){
                    td.setAttribute('rowSpan', '2');
                }
            }
        }
    }
    body.appendChild(tbl);
}
tableCreate();

また、これはCSSを使用する代わりにborder属性を設定するなどの「悪い習慣」を使用せず、document.getElementsByTagName('body')[0]の代わりにbodyからdocument.bodyにアクセスします。

102
Cerbrus
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();
<div id="myDynamicTable"></div>
9
Nitin Pawar
<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>
5
user3802764

私はあなたがこれが参考になることを願っています。

HTML:

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

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

ジャバスクリプト:

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);
3
Shubham Arya
<!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>
3
Rajiv Bhardwaj
This is how to loop through a javascript object and put the data into a table.
    <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.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> </code>
0
Giovanni Gianni

この特定の質問で説明されている問題を解決しないかもしれませんが、オブジェクトの配列からテーブルを作成しようとしている人々には役に立つかもしれません:

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']);
0
Vanuan
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>Heading</th>' +
    '<th>Heading</th> ' +
    '<th>Heading</th>' +
  '</tr>' +
  '<tr>' +
    '<td>cell</td>' +
    '<td>cell</td>' +
    '<td>cell</td>' +
  '</tr>' +
  '<tr>' +
    '<td>cell</td>' +
    '<td>cell</td>' +
    '<td>cell</td>' +
  '</tr>' +
  '<tr>' +
    '<td>cell</td>' +
    '<td>cell</td>' +
    '<td>cell</td>' +
  '</tr>'
};
0
vicky patel