2014-12-03 75 views
0

我使用Bootstrap 3的模態類和Datatables 1.10創建一個包含動態數據表的確認模態對話框。每次顯示模式時,我都需要替換表中的行,因此我使用數據表API來動態地清除和添加行。我遇到的問題是數據表創建另一個表並向它添加行,而不是將行添加到包含標題的現有表。下面是一些標記,JavaScript和一個JSFiddle的鏈接,說明了這種行爲。Bootstrap 3.2 modal with Datatables 1.10 API row.add

我在這裏做錯了什麼?這是一個數據表錯誤?

JSFiddle illustrating this behavior

HTML

<body> 
<div id="theModal" class="modal fade" hidden="true"> 
    <div class="modal-dialog"> 
    <div class="modal-content"> 
     <div class="modal-header"> 
     <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> 
     <h4 class="modal-title">Confirmation</h4> 
     </div> 
     <div class="modal-body"> 
     <div> 
      <table id="foobar" class="table table-condensed table-striped table-bordered small"> 
       <thead> 
        <th>col 1</th> 
        <th>col 2</th> 
        <th>col 3</th> 
        <th>col 4</th> 
       </thead> 
       <tbody> 
       </tbody> 
      </table> 
     </div> 
     </div> 
    </div><!-- /.modal-content --> 
    </div><!-- /.modal-dialog --> 
</div><!-- /.modal --> 


<div class="container-fluid"> 
    <div class="row"> 
     <div class="col-xs-6"> 
      <a href="#" id="theButton" role="button" class="btn btn-primary" >show modal</a> 
     </div> 
    </div> 
</div> 
</body> 

的JavaScript時創建表時被隱藏

var theTable; 
$(document).ready(function(){ 

    $('#theButton').click(function(e) { 
      // just illustrating my dynamic data.... 
      var data = ['data 1', 'data 2', 'data 3', 'data 4'] 
      showTheModalTable(data); 
    }); 

    theTable = $('#foobar').dataTable({ 
     "searching": false, 
     "ordering": false, 
     "paging" : false, 
     "scrollY": "300px", 
     "scrollCollapse": true, 
     "info" : true 
    }); 

}); 

function showTheModalTable(data){ 

    theTable.api().clear();   
    theTable.api().row.add(data); 

    $('#theModal').modal(); 
    theTable.api().draw(); 
} 

回答

2

http://jsfiddle.net/2Lo1qzk2/12/

DataTable中有問題。使用模擬事件shown.bs.modal並在此刻定義您的數據表並添加行

var theTable; 
$(document).ready(function() { 

    $('#theButton').click(function (e) { 

     showTheModalTable(); 
    }); 

    theTable = $('#foobar').dataTable({ 
     "searching": false, 
      "ordering": false, 
      "paging": false, 
      "scrollY": "300px", 
      "scrollCollapse": true, 
      "info": true 
    }); 

}); 

function showTheModalTable() { 
    $('#theModal').modal(); 
} 

$('#theModal').on('shown.bs.modal', function (e) { 
    var data = ['data 1', 'data 2', 'data 3', 'data 4'] 
    theTable.api().clear(); 

    theTable.api().row.add(data).draw(); 
})