如何动态地在html表中插入行

时间:2014-10-30 03:10:14

标签: jquery html

我想在我的table中动态插入一行,但我没有运气来实现这一目标。

在我的ajax成功中,这是我插入表格行的方式

$('#mytable').find('tbody').append(data); 

HTML:

<table  class="display" id="mytable" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>#</th>
      <th>FIRST NAME</th>
      <th>LAST NAME</th>
      <th>ADDRESS</th>
      <th>AGE</th>
    </tr>
  </thead>
  <tbody>
    // I want to insert here.
  </tbody>
</table>

这是要返回的数据。

<tr class="myclass">
  <td style="text-align: center;">1</td>
  <td>Jack</td>
  <td>Miller</td>
  <td>California</td>
  <td>24</td>    
</tr>
<tr class="myclass">
  <td style="text-align: center;">2</td>
  <td>Miguel</td>
  <td>Park</td>
  <td>London</td>
  <td>64</td>     
</tr>

提前谢谢。

2 个答案:

答案 0 :(得分:1)

使用每个循环并通过追加方法

使用HTML追加数据
  $.each(data,function(value,index){}{

     $('#mytable').find('tbody').append("<tr><td>"+value+"</td></tr>"); 

  });{

答案 1 :(得分:0)

它将动态添加行..

<!DOCTYPE html>
    <html>
    <head>
    <style>
    table, td {
        border: 1px solid black;
    }
    </style>
    </head>
    <body> 
<table id="myTable">
  <tr>
    <td>Row1 cell1</td>
    <td>Row1 cell2</td>
  </tr>
  <tr>
    <td>Row2 cell1</td>
    <td>Row2 cell2</td>
  </tr>
  <tr>
    <td>Row3 cell1</td>
    <td>Row3 cell2</td>
  </tr>
</table>
<br>

<button onclick="myFunction()">Add row</button>

<script>
function myFunction() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(0);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = "NEW CELL1";
    cell2.innerHTML = "NEW CELL2";
}
</script>

</body>
</html>
相关问题