2012-10-09 39 views
1

我有一個<select>,每個用戶改變其選擇的選項的時候,我想不同的jQuery的數據表來繪製(使用隱藏的DOM <table>作爲數據源):如何讓jQuery DataTables在多個DOM表之間切換?

<!-- Assume I have included jquery.dataTables.css and jquery.dataTables.js correctly. --> 

<style> 
    #hidden-tables { 
     display: hidden; 
    } 
</style> 

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#table1").dataTable(); 
     $("#table2").dataTable(); 
    }); 
</script> 

<select id="my-sel"> 
    <option selected="selected" id="opt1">Nothing selected</option> 
    <option id="opt1">Opt1</option> 
    <option id="opt2">Opt2</option> 
</select> 

<div id="hidden-tables"> 
    <table id="table1"> 
     <!-- Omitted for brevity --> 
    </table> 
    <table id="table2"> 
     <!-- Omitted for brevity --> 
    </table> 
</div> 

<!-- When the user selects opt1 or opt2 in the "my-sel" <select>, then display its corresponding table here. --> 
<div id="table-to-show"></div> 

基本上,在頁面加載的時候了,我想my-sel選擇顯示「沒有選擇」並且沒有繪製表格。當用戶選擇除「沒有選擇」之外的任何內容時,我想讓相應的jQuery DataTable在table-to-show div內繪製。提前致謝!

回答

0

一種解決方案可能是像

<div class="show"> 
    <table id="table1"> 
     <!-- Omitted for brevity --> 
    </table> 
</div> 
<div class="hide"> 
    <table id="table2"> 
     <!-- Omitted for brevity --> 
    </table> 
</div> 

其中

.hide {display:none;} 

.show {display:block;} 

所有您需要做的是,當你選擇從不同的選項切換類選擇下拉...

0

嘗試......

替換此...

<script type="text/javascript"> 
$(document).ready(function() { 
    $("#table1").dataTable(); 
    $("#table2").dataTable(); 
}); 
</script> 

有了這個..

<script type="text/javascript"> 
$(document).ready(function() { 
    $('#my-sel').change(function() { 
     var opt = $(this).find('option:selected').html(); 
     if (opt !== 'Nothing selected') { 
      $('#table-to-show').html(''); 
      var tableName; 
      switch (opt) { 
       case 'Opt1': 
        tableName = 'table1'; 
        break; 
       case 'Opt2': 
        tableName = 'table2'; 
        break; 
      } 
      $('#' + tableName).clone(true).appendTo('#table-to-show'); 
      $('#table-to-show table').dataTable(); 
     } 
    }); 
}); 
</script> 

也能改變你display:hidden;display:none; 「隱藏」 用於CSS屬性「可見「不」顯示「

希望有幫助!