【问题标题】:Multiple datatables under different tabs, one with Ajax source不同选项卡下的多个数据表,一个带有 Ajax 源
【发布时间】:2011-04-27 21:03:11
【问题描述】:

我在 2 个选项卡下有 2 个表格。默认选项卡下的表格很好地显示了数据表。第二个表是从 Ajax 源(JSON 数组)填充的。问题是我无法使用 DataTables 初始化此表。

$(document).ready(function() {

    //When page loads...
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tabs li").click(function() {

        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content

        var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
        if(activeTab == "#tab2"){   
        $.getJSON("<url>",              
            function(data) {
                    htmlTable = '<table id="table2" cellspacing="1" cellpadding="1" border="1">'; 
                                    htmlTable+=<data...>;
                    htmlTable +='</tbody></table>';
                        $('#table2').remove();
                        $('#tab2').append(htmlTable);
            });

        }

               $(activeTab).fadeIn(); //Fade in the active ID content
        return false;
    });

});

如果我在 getJSON() 调用的成功函数中显式初始化,我会在每次单击选项卡时看到多个这样的 DataTable。如何初始化这个dataTable...

【问题讨论】:

  • 我通过显式初始化 dataTables 在检查是否存在并删除它之后修复了这个问题:'if ($("#table2_wrapper").length > 0){ $( '#table2_wrapper').remove(); }'

标签: jquery ajax datatables


【解决方案1】:

我有一些问题。当 dataTables 具有内置功能时,您为什么要使用 $,getJSON()?为什么要在选项卡的onclick 动态创建表格?如果您只想在单击第二个选项卡时加载表格内容然后制作一个静态表格并将 dataTables 初始化代码放在 onclick tab2 代码中

HTML

<div id="tab2" class="tab_content">
  <table class="display dataTable" id="table2">
    <thead>
      <tr>col1</tr>
       ....
    </thead> 
    <tbody>
    </tbody>
  </table>
</div>

jQuery

$("ul.tabs li").click(function() {

        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content

        var activeTab = $(this).find("a").attr("href"); 
        if(activeTab == "#tab2"){          
           oTable2 = $('#table2').dataTable({
            "bProcessing": true,
                "sAjaxSource": "yourURL"
        }
        $(activeTab).fadeIn(); //Fade in the active ID content
        return false;
    });

如果内容的大小不太大,我仍然认为您应该在页面加载时加载第二个表格,而不是在单击第二个选项卡时加载

【讨论】:

  • 您的建议给了我错误。该表通过 getJSON 填充了 JSON 数组。
  • 这就是我所说的,如果您使用 ajax 和 json 那么为什么要使用 getJSON 方法为什么不使用 dataTable 插件提供的 ajaxSource 功能来实现此目的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
  • 1970-01-01
相关资源
最近更新 更多