2016-11-26 16 views
1

Ich versuche, dynamische Tabelle mit Bootstrap zu tun, aber ich kann nicht ableiten, warum es nicht funktioniert. Es gibt einen HTML-Teil:Dynamische Tabelle mit bootstrap

<div class="container"> 
     <button onclick="CreateTable()">Extend</button>   
     <table class="table"> 
      <thead> 
       <tr> 
        <th>Employee Id</th> 
        <th>Name</th> 
        <th>Country</th> 
       </tr> 
      </thead> 
      <tbody> 
       <tr> 
        <td>1</td> 
        <td>John Doe</td> 
        <td>Country1</td> 
       </tr> 
       <tr> 
        <td>2</td> 
        <td>Mary Moe</td> 
        <td>Country2</td> 
       </tr> 
       <tr> 
        <td>3</td> 
        <td>Jack Dooley</td> 
        <td>Country3</td> 
       </tr> 
       <p id="id_tabela"></p> 
      </tbody> 
     </table> 
    </div> 

und es gibt javascript:

 function CreateTable() { 
      var employee = new Array(); 
      employee.push([4, "Billie Jean", "Country4"]); 
      employee.push([5, "Harish Kumar", "Country5"]); 
      employee.push([6, "Pankaj Mohan", "Country6"]); 
      employee.push([7, "Nitin Srivastav", "Country7"]); 
      employee.push([8, "Ramchandra Verma", "Country8"]); 

      var tablecontents = ""; 
      for (var i = 0; i < employee.length; i++) { 
       tablecontents += "<tr>"; 
       for (var j = 0; j < employee[i].length; j++) { 
        tablecontents += "<td>" + employee[i][j] + "</td>"; 
       } 
       tablecontents += "</tr>"; 
      } 
      document.getElementById("id_tabela").innerHTML = tablecontents; 
     } 

Deshalb möchte ich die Tabelle erweitern und ich kann nicht herausfinden, warum es nicht funktioniert.

+0

employee.push ({4, "Billie Jean" , "Land4"}); Aktualisierung auf geschweifte Klammern. – Dev

Antwort

1

Sie laden die Daten innerhalb den Absatz, der nicht das ist, was Sie tun möchten. Auch der Absatz sollte nicht da sein. Sie können id zu tbody hinzufügen und dann einfach seine innerHTML wie folgt erweitern: https://jsfiddle.net/14pt76wp/.

Warum verwenden Sie native Funktionen? Bootstrap enthält jQuery.

$('table tbody').append(tablecontents); 

Ein weiterer Trick: Man könnte so etwas wie tun

  1. Iterate über die Anordnung und tun
    employee[i] = '<td>' + employee[i].join('</td><td>') + '</td>';
  2. tablecontents = '<tr>' + employee.join('</tr><tr>') + '</tr>';
+0

Danke :) Du bist großartig – TheAdrik94