为什么引导动态表分页不能工作

Why bootstrap dynamic table pagination is not working?

本文关键字:分页 不能 工作 动态 为什么      更新时间:2023-09-26

我正在研究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>

在上面的代码中,你可以看到在静态内容中,它能够计算行数,但在动态内容中,它无法计算表中有多少行,因为表是动态创建的。

请仔细检查我上面的代码,如果你有任何解决方案,请告诉我。

谢谢

您的代码不工作,因为您在文档准备就绪的时刻调用初始化对象(使用$('#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" }
        ]
    } );
    

在这里您可以找到第二个选项的文档。

希望有帮助!