2017-02-10 36 views
2

我想通過使用數組添加td,下面是給定的示例。我如何完成<tr>標籤,其中包含陣列中的完整詳細信息。用jquery插入錶行數據

$(document).ready(function() { 
 
     $('#myTable > tbody:last-child').append('<tr><td>8:30am</td></tr>'); 
 
var timing = ['14:30' , '21:00']; 
 
    $.each(timing,function(i,v){ 
 
    //how can i enter the remaining data using array to complete the <tr> tag 
 
    }) 
 
} 
 
       
<table id="myTable" class="table"> 
 
         <thead> 
 
          <tr> 
 
           <th>Morning</th> 
 
           <th>Afternoon</th> 
 
           <th>Evening</th> 
 
           </tr> 
 
          </thead> 
 
         <tbody> 
 
          <tr id="months_row"> 
 
           
 
          </tr> 
 
         
 
         </tbody> 
 
        </table>

回答

1

使用Array#map方法來生成tr元素,並將它附加到先前創建tr

$(document).ready(function() { 
 
    $('#myTable > tbody:last-child').append(
 
    // wrap to make it jQuery object 
 
    $('<tr><td>8:30am</td></tr>') 
 
    // append the td's to the tr 
 
    .append(
 
     // generate the td's array 
 
     ['14:30', '21:00'].map(function(v) { 
 
     // generate td with the text 
 
     return $('<td>', { 
 
      text: v 
 
     }); 
 
     }) 
 
    ) 
 
) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="myTable" class="table"> 
 
    <thead> 
 
    <tr> 
 
     <th>Morning</th> 
 
     <th>Afternoon</th> 
 
     <th>Evening</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    <tr id="months_row"> 
 

 
    </tr> 
 

 
    </tbody> 
 
</table>


或產生的HTML字符串追加。

$(document).ready(function() { 
 
    $('#myTable > tbody:last-child').append(
 
    '<tr><td>8:30am</td>' + ['14:30', '21:00'].map(function(v) { 
 
     return '<td>' + v + '</td>' 
 
    }).join('') + '</tr>' 
 
) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="myTable" class="table"> 
 
    <thead> 
 
    <tr> 
 
     <th>Morning</th> 
 
     <th>Afternoon</th> 
 
     <th>Evening</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    <tr id="months_row"> 
 

 
    </tr> 
 

 
    </tbody> 
 
</table>

+0

我想添加的所有數據在單一標記,以便該表將完全相等行和coloums.can你? – muther

+0

@muther:已更新 –