如何为每一行设置setInterval,时间来自后端JSON。从那时起需要每秒增加时间吗?
var el = $('#feedback_tasks_list tbody');
el.empty();
for(var i = 0 ; i < timeList.length ; i++)
{
var tableRow = $('<tr class = "time_row" data-TIME-id="'+ timeList[i].id+'"></tr>');
tableRow.appendTo(el);
$('<td></td>').html(timeList[i].customerName).appendTo(tableRow);
$('<td></td>').html(secToMin(timeList[i].fromTime)).appendTo(tableRow);
}
// Seconds to minutes or hour
var secToMin = function(seconds){
var sec = parseInt(seconds);
if(sec < 60){
if(sec < 10)
{
sec = '0'+sec;
}
return('00:00:'+sec);
}
else if(sec >= 60 && sec < 3600){
var min = parseInt(sec/60);
if(min < 10)
{
min = '0'+min;
}
var remainingSec = parseInt(sec%60);
if(remainingSec < 10)
{
remainingSec = '0'+remainingSec;
}
return('00:'+min+':'+remainingSec);
}
else{
var hour = parseInt(sec/3600);
if(hour < 10)
{
hour = '0'+hour;
}
var remainingHour = parseInt(sec%3600);
var min = parseInt(remainingHour/60);
if(min < 10)
{
min = '0'+min;
}
var remainingSec = parseInt(remainingHour%60);
if(remainingSec < 10)
{
remainingSec = '0'+remainingSec;
}
return(hour+':'+min+':'+remainingSec);
}
}
如果我从后端获得150秒secToMin(timeList [i] .fromTime)正在显示00:02:30。 之后我需要每秒增加一秒。为什么如何使用setIntrval,以及从哪里调用该函数。 请帮助。
答案 0 :(得分:1)
你可以创建一个新的数组/对象,它只保存每一行的实际时间值(让我们称之为times
),然后在setInterval回调中循环遍历所有这些值,递增它们并重新计算每一行的值。
这是一个简单的例子:
var times = [123, 431, 1]; // simulating times data
var divs = document.querySelectorAll('div'); // get all the elements
setInterval(function() {
for (var i = 0; i < divs.length; i++) { // loop through them
// increment each, recalculate and modify HTML
divs[i].textContent = secToMin(++times[i]);
}
}, 1000);
// Seconds to minutes or hour
var secToMin = function(seconds){
var sec = parseInt(seconds);
if(sec < 60){
if(sec < 10)
{
sec = '0'+sec;
}
return('00:00:'+sec);
}
else if(sec >= 60 && sec < 3600){
var min = parseInt(sec/60);
if(min < 10)
{
min = '0'+min;
}
var remainingSec = parseInt(sec%60);
if(remainingSec < 10)
{
remainingSec = '0'+remainingSec;
}
return('00:'+min+':'+remainingSec);
}
else{
var hour = parseInt(sec/3600);
if(hour < 10)
{
hour = '0'+hour;
}
var remainingHour = parseInt(sec%3600);
var min = parseInt(remainingHour/60);
if(min < 10)
{
min = '0'+min;
}
var remainingSec = parseInt(remainingHour%60);
if(remainingSec < 10)
{
remainingSec = '0'+remainingSec;
}
return(hour+':'+min+':'+remainingSec);
}
}
&#13;
<div></div>
<div></div>
<div></div>
&#13;
因此,在您的情况下,您可以为那些保留时间的单元格添加一个类(只是为了让选择更容易):
$('<td class="timeHolder"></td>').html(secToMin(timeList[i].fromTime)).appendTo(tableRow);
然后在setInterval回调中,你做的就像我在上面的例子中所做的那样:
var $timeHolders = $('.timeHolder');
setInterval(function(){
for(var i = 0; i < $timeHolders.length; i++) {
$timeHolders.eq(i).html(secToMin(++timeList[i].fromTime));
}
}, 1000);