为什么bootstrap动态表分页不起作用?

时间:2016-10-29 07:45:17

标签: javascript pagination

我正在研究Bootstrap表的分页,但有一件事我发现它在静态内容上运行良好,但在动态内容中它并不起作用。

静态代码

<script>
 $(document).ready(function() {
     $('#example').DataTable();
 });
</script>

<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>USN</th>
            <th>Name</th>
            <th>Branch</th>
            <th>Batch</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
        </tr>
        <tr>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
        </tr>
    </tbody>
</table>

动态表

<script>
$(document).ready(function() {
   $('#example').DataTable();
});
</script>

<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>USN</th>
            <th>Name</th>
            <th>Branch</th>
            <th>Batch</th>
        </tr>
    </thead>
    <tbody id="user_list">
    </tbody>
</table>

<script>
var ref = firebase.database().ref("Students/");
var newTable='';

ref.on('child_added', function(snapshot) {
    snapshot.forEach(function(snap) {

        var usn = snap.val().usn;
        var name = snap.val().studentName;
        var colname = snap.val().collegeName;
        var branch = snap.val().branch;
        var batch = snap.val().batch;   

        newTable+='<tr data-value='+usn+' id='+usn+'>';
        newTable+='<td>'+usn+'</td>';
        newTable+='<td>'+name+'</td>';
        newTable+='<td>'+branch+'</td>';
        newTable+='<td>'+batch+'</td>';
        newTable+='</tr>';
        document.getElementById('user_list').innerHTML=newTable;
    });
 });
</script>

因此,我可以在静态内容中看到它能够计算行数,但在动态内容中,由于表是动态创建的,所以无法计算表中有多少行。

请仔细阅读上述代码,如果您有任何解决方案,请告诉我。

由于

1 个答案:

答案 0 :(得分:0)

您的代码无效,因为您在文档准备好之前,在生成数据之前调用初始化对象(使用$('#example').DataTable();)。

你有(至少)两个选择:

  1. 生成动态数据后,请致电$('#example').DataTable(); 类似的东西:

    ref.on('child_added', function(snapshot) {
        snapshot.forEach(function(snap) {
            var usn = snap.val().usn;
            // more code
            document.getElementById('user_list').innerHTML=newTable;
            $('#example').DataTable();
        });
    });
    
  2. 您使用snapshot函数生成的不是表格,而是生成数据集。然后,使用初始化对象中的内置data选项,传入数据集。

    var dataSet = [
        [ "Tiger Nixon", "System Architect", "Edinburgh", "61" ],
        [ "Garrett Winters", "Accountant", "Tokyo", "63" ]
    ];
    
    $('#example').DataTable( {
        data: dataSet,
        columns: [
            { title: "Name" },
            { title: "Position" },
            { title: "Office" },
            { title: "USN" }
        ]
    } );
    
  3. Here you will find the documentation第二个选项。

    希望它有所帮助!