如何让jQuery DataTables在多个DOM表之间切换?

时间:2012-10-09 19:54:33

标签: javascript jquery datatables

我有一个<select>,每次用户更改其选择的选项时,我都希望绘制一个不同的jQuery数据表(使用隐藏的DOM <table>作为数据源):

<!-- 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选择显示“ Nothing selected ”并且没有绘制表格。当用户选择“ Nothing selected ”以外的任何内容时,我希望在table-to-show div内绘制相应的jQuery DataTable。提前谢谢!

2 个答案:

答案 0 :(得分: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;}

当您从选择下拉列表中选择不同的选项时,您所要做的就是切换类...

答案 1 :(得分: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; “hidden”用于css属性“visible”而不是“display”

希望有所帮助!