gpt4 book ai didi

javascript - 排序时,表体为空

转载 作者:行者123 更新时间:2023-11-30 20:06:42 25 4
gpt4 key购买 nike

当我在任何行上单击排序时,表体是空的。我从 firebase 加载数据,然后在我能够检索数据后将其附加到表体上。

这是我的html代码

<div class="card" style="padding: 10px; margin: 50px;">
<table id="myTable" class="display table-responsive-sm">
<thead>
<tr>
<th>Last activity</th>
<th>Email</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody id="tableBody">

</tbody>
</table>
</div>

这是我的 javascript 代码,它只是初始化数据表并通过 loadUsers 函数从 firebase 检索数据

$(document).ready( function () {
$('#myTable').DataTable();
} );

window.onload = function(){
admin.load();
}

var admin = {

database: null,

load: function(){
firebase.initializeApp(config);
this.database = firebase.database();
this.loadUsers();
},

loadUsers:function(){
let usersRef = this.database.ref('users');
usersRef.orderByChild("info/lastMessage").on("value", (snapshot) => {
$('#tableBody').empty();
snapshot.forEach((child) => {
$('#tableBody').append('\
<tr>\
<td>'+moment(child.val().info.lastMessage).format('D MMM h:mm:ss A')+'</td>\
<td>'+child.val().info.email+'</td>\
<td align="center"><button data-toggle="modal" data-target="#exampleModal" type="button" class="btn btn-sm btn-outline-danger">Block</button></td>\
<td align="center"><button type="button" class="btn btn-sm btn-outline-danger">Delete Messages</button></td>\
</tr>\
')
});
});
},
}

here is the loaded html

when i click  sor, here it is

最佳答案

您在 ready 事件中初始化 DataTables 插件,该事件发生在 load 事件中,您在其中添加表数据。

相反,您需要在添加数据后初始化 DataTables 插件。

例如(未测试):

$(window).on('load', function() {
admin.load();
$('#myTable').DataTable();
});

我不熟悉 Firebase,但如果它在数据可用时返回 Promise,那么您需要初始化 DataTables 插件作为对事件发生时的响应。

或者,您可以在获取数据之前初始化 DataTables 插件并使用 row().add()向表中添加数据的 API 方法。这可能是首选,因为它看起来比生成 HTML 标记要干净得多。

关于javascript - 排序时,表体为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52846098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com