[英]Datatables footer sum()
我正在尝试对hh:mm:ss类型的数据进行正确的sum()处理,并且我试图理解为什么当分钟或秒数变得> = 100时为什么会有这种行为。我该如何解决呢? ?
这是我从Datatables论坛获取的sum()函数:
jQuery.fn.dataTable.Api.register('sum()', function () {
return this.flatten().reduce(function (a, b) {
if (typeof a === 'string') {
a = a.replace(/[^\d.-]/g, '') * 1;
}
if (typeof b === 'string') {
b = b.replace(/[^\d.-]/g, '') * 1;
}
return a + b;
}, 0);
});
这是剩下的所有充满转换的代码,这让我很头疼。
var tempoPage = tempo.column(3, { page: 'current' })
.data()
.sum();
tempoPage = tempoPage.toString();
while (tempoPage.length < 6) {
tempoPage = "0" + tempoPage
}
tempoPage = tempoPage.replace(/^(\d+)(\d{2})(\d{2})$/, function (m, m1, m2, m3) {
m1 = Number(m1);
m2 = Number(m2);
m2 += parseInt(m3 / 60, 10);
m3 = m3 % 60; // get soconds
m1 += parseInt(m2 / 60, 10); //get hours
m2 = m2 % 60; // get minutes
//convert back to string
m2 = m2.toString();
m3 = m3.toString();
m1 = m1.toString();
while (m1.length < 2){
m1 = '0' + m1
}
while (m2.length < 2){
m2 = '0' + m2
}
while (m3.length < 2){
m3 = '0' + m3
}
return m1 + ':' + m2.slice(-2) + ':' + m3.slice(-2);
})
//write in footer
$(tempo.column(3)
.footer()).html(tempoPage);
},
有没有人看到一种更好的方法来做到这一点,或者可以指出我的正确方向? 谢谢。
我不能说代码有什么问题。 看起来确实很复杂,我们唯一需要做的就是对3个值求和,例如在秒数增加60时加1分钟。使这个不太复杂的sumHours()
插件看起来很有效(但尚未测试)深度):
jQuery.fn.dataTable.Api.register( 'sumHours()', function ( ) {
function pad(int) {
return int > 9 ? int.toString() : '0' + int.toString()
}
var t, hours = 0, mins = 0, secs = 0;
for (var i=0; i<this.length; i++) {
t = this[i].split(':')
hours += parseInt(t[0])
mins += parseInt(t[1])
if (mins >= 60) {
mins -= 60
hours += 1
}
secs += parseInt(t[2])
if (secs >= 60) {
secs -= 60
mins += 1
}
}
return pad(hours) + ':' + pad(mins) + ':' + pad(secs)
})
您可以使用与链接到官方sum()
示例相同的方式使用此方法:
api.column( 0, {page:'current'} ).data().sumHours()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.