繁体   English   中英

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

[英]How to get jQuery DataTables to switch between multiple DOM tables?

我有一个<select> ,每次用户更改其选择的选项时,我都希望绘制一个不同的jQuery Datatable(使用隐藏的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。 提前致谢!

一种解决方案可能是类似

<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;}

您只需从选择下拉列表中选择不同的选项即可切换类。

尝试这个...

取代这个...

<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属性“可见”而不是“显示”

希望有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM