开发者

Multiple datatables under different tabs, one with Ajax source

I have 2 tables under 2 tabs. The table under default tab shows the datatables fine. The second table is populated from Ajax source (JSON array). Problem is I am not able to initialize this table with DataTables.

$(document).ready(function() {

    //When page loads...
    $(".tab_c开发者_如何学编程ontent").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;
    });

});

If I explicitly initialize in the success function of the getJSON() call, I see multiple such DataTables on every click of the tab. How to initialize this dataTable...


I have some questions.Why are you using $,getJSON() when dataTables has inbuilt functionality for that? Why are you creating the table dynamically onclick of the tab?IF you want to load the table content only on clicking of second tab then make a static table and put the dataTables initialization code inside the onclick tab2 code

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

I still think you should load the second table on page load not on clicking of second tab if the size of the content is not too large

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜