简体   繁体   中英

Create complex table body structure using Javascript

Could anybody tell me how I can create this table using my function below?

<tbody>
 <tr>
  <td><h3>Main1</h3></td>
  <td>
    <h5>
      text1
    </h5>
  </td>
  <td>
    <h5>
     text2
    </h5>
  </td>
 </tr>
 <tr>
   <td><h3>Main2</h3></td>
   <td>
    <h5>
      text3
    </h5>
   </td>
   <td>
    <h5>
      text4
    </h5>
   </td>
 </tr>
</tbody>

Here are my data and my functions. I can only create a table without the inner h3, h5 tags with it.

data =[['Main1', 'text1', 'text2'],['Main2', 'text3', 'text4']]

  var table = document.getElementsByTagName("tbody")[0];
      table.innerHTML = ""; 
      for (var i = 0; i < data.length; i++) {
        var child = data[i];
        var row = table.insertRow();
        Object.keys(child).forEach(function (k) {
          var cell = row.insertCell();
          cell.appendChild(document.createTextNode(child[k]));

Try using javascript string interpolation:

 data =[['Main1', 'text1', 'text2'],['Main2', 'text3', 'text4']] var table = document.getElementsByTagName("tbody")[0]; table.innerHTML = ""; for (var i = 0; i < data.length; i++) { var row = table.insertRow(); row.innerHTML = `<tr><td><h3>${data[i][0]}</h3></td><td>${data[i][1]}</td><td>${data[i][2]}</td></tr>`; }
 <table> <tbody> </tbody> </table>

But this attitude is quite obsolete, I strongly recomend using modern binding frameworks like Vue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM