我有一个脚本可以初始化数据表并每隔几秒重新加载内容。
我想添加
onclick
事件处理程序,但不确定如何构建文件。现在的情况是,页面刷新时会触发 openPoolModal
功能,而无需发生任何点击。这会导致 DataTables
初始化失败,因为模式对话框已打开且不存在表格。
当我在
onclick
初始化后移动 DataTables
线时,getElementById
仅返回 null。
var table;
$(document).ready(function() {
$('#main-table').on("click", "tr", openPoolModal(document.getElementById("hashrateId").innerText));
table = $('#main-table').DataTable({
ajax: {
url: '/refresh',
dataSrc:''
},
paging: true,
lengthChange: false,
pageLength: 20,
stateSave: true,
info: true,
searching: false,
"columnDefs": [
{
"className": "text-center",
"targets": 0,
"data": "id",
},
{
"className": "text-center",
"targets": 1,
"data" : function(data){
var seconds = data.repDate.second < 10 ? seconds = "0" + data.repDate.second : seconds = data.repDate.second;
var minutes = data.repDate.minute < 10 ? minutes = "0" + data.repDate.minute : minutes = data.repDate.minute;
var months = data.repDate.monthValue < 10 ? months = "0" + data.repDate.monthValue : months = data.repDate.monthValue;
var days = data.repDate.dayOfMonth < 10 ? days = "0" + data.repDate.dayOfMonth : days = data.repDate.dayOfMonth;
return data.repDate.year + "-" + months + "-" + days + " " + data.repDate.hour + ":" + minutes + ":" + seconds;
},
},
{
"className": "text-center",
"targets": 2,
"data": function(data){
return data.hashrate/1000.0;
},
}
],
"aoColumns": [
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "desc", "asc" ] }
],
"order": [[ 0, "asc" ]]
});
});
setInterval(function(){
table.ajax.reload(null, false);
}, 8000);
我也尝试过这样的点击实现,但结果相同:
$('#main-table').on('click', 'tr', function () {
var id = document.getElementById("hashrateId").innerText;
console.log(id);
openPoolModal(document.getElementById("hashrateId").innerText);
} );
HTML表格:
<table class="table table-hover" id="main-table">
<thead class="thead-inverse">
<tr >
<th class="col-md-2 text-center">Network Id</th>
<th class="col-md-2 text-center">Rep date</th>
<th class="col-md-2 text-center">Hashrate [KH/s]</th>
</tr>
</thead>
<tbody>
<tr id="tableRow" style="cursor: pointer;" th:each="networkHashrate : ${networkHashrates}" th:onclick="'javascript:openPoolModal(\''+ ${networkHashrate.id} + '\');'">
<td class="text-center" id="hashrateId" th:text="${networkHashrate.id}"> Sample id</td>
<td class="text-center" id="repDate" th:text="${@findAndDisplayDataService.formatDate(networkHashrate.repDate)}">Sample rep-date</td>
<td class="text-center" id="hashrate" th:text="${@findAndDisplayDataService.formatHashrate(networkHashrate.hashrate)}">Sample hashrate</td>
</tr>
</tbody>
</table>
我现在将尝试通过事件委托来回答
$(document).on('click', '#main-table tbody tr', function () {
var hashrateId = $(this).find("td").eq(0).text();
console.log(hashrateId);
//openPoolModal(hashrateId);
});
将此代码与您拥有的其他代码分开放置。