Jquery动态创建的表行与引导程序表头不对齐

时间:2017-07-10 12:31:51

标签: jquery twitter-bootstrap-3 html-table

我使用了以下stackoverflow问题Javascript / jQuery: How to dynamically add rows to table body (using arrays)的答案,以实现动态添加表行。我也使用bootstrap主题。添加正确完成,但<td>未与<th>对齐。

我的html代码如下:

    <div class="row" id="dynamic_table">
                  <div class="col-lg-12">
                      <div class="panel panel-default">
                          <div class="panel-heading">
                          </div>
                          <div class="panel-body center">
                             <table class="table">
                             <thead>
                               <tr>
                                 <th>Header 1</th>
                                 <th>Header 2</th>
                                 <th>Header 3</th>
                                 <th>Header 4</th>
                               </tr>
                             </thead>
                             <tbody id="table_body">
                             </tbody>
                           </table>
                          </div>
                    </div>
                </div>
        </div>

虽然jQuery代码如下:

tbody = "<tr><td>" + value1 +"</td><td>" + value2 +"</td><td>" + value3 + "</td><td>" + value4 +"</td></tr>";
$('#table_body').html(tbody);

由于我在bootstrap框架和jQuery中都很新,我应该怎么做才能使值与相关的标题对齐?

1 个答案:

答案 0 :(得分:1)

你在找这个:

/*for testing dynamic values */
var testData = [1,2,3,4,5];

$.each(testData,function(index, value){
var tBody = '<tr><td>row-'+value+'</td><td>row-'+value+'</td><td>row-'+value+'</td><td>row-'+value+'</td></tr>';
$('#table_body').append(tBody);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<style> td,th{border:1px solid #ddd;vertical-align:top;} tr{margin:0;}</style>
<div class="row" id="dynamic_table">
                  <div class="col-lg-12">
                      <div class="panel panel-default">
                          <div class="panel-heading"> Dynamic Table
                          </div>
                          <div class="panel-body center">
                             <table class="table">
                             <thead>
                               <tr>
                                 <th>Header 1</th>
                                 <th>Header 2</th>
                                 <th>Header 3</th>
                                 <th>Header 4</th>
                               </tr>
                             </thead>
                             <tbody id="table_body">
                             </tbody>
                           </table>
                          </div>
                    </div>
                </div>
        </div>