Updating Table with Refresh

2020-05-07 04:45发布

I have a jquery app which consist of a table. The table has a time field and some number fields. I want to basically increment the values every 3 seconds. So i was thinking of creating a function where i increment the number values and calling it via refresh functions that auto refreshes every 3 seconds.

so basically originally the information is as follows

Kobe Bryant 10:00 30 4 2

after 3 seconds it should be

Kobe Bryant 10:03 31 5 4

This is the Fiddle i have made.

I was not able to do this. I tried to make a function where i increase the table values and call that function as such

setInterval(updateFunction, 3000);

but no luck. This is how i was thinking of creating a function.

var cell = $("#example");
var currentVal = parseInt(cell.text(), 10);
cell.text( currentVal + 1 );

Can anyone please provide some advice. I am new to js and jquery and also sorry for poor english if its hard to understand i can clarify what i mean.

2条回答
家丑人穷心不美
2楼-- · 2020-05-07 05:00

Here is a way. Add classes to the cells that need updating:

<td>Lebron James</td>
<td class="updateMeTime">08:00</td>
<td class="updateMeInt">27</td>
<td class="updateMeInt">11</td>
<td class="updateMeInt">10</td>

In this example, the class updateMeInt means it is a simple integer, and updateMeTime means it is a time value.

Then your update function would iterate through each cell with these classes and increment:

function UpdateFunction(){
    $(".updateMeInt").each(function(index){
       var cur = parseInt($(this).text(), 10);
       $(this).text(cur + 1);    
    });

    $(".updateMeTime").each(function(index){
        var cur = $(this).text().split(":");    
        var sec = parseInt(cur[1], 10);        
        var min = parseInt(cur[0], 10);

        sec = sec + 3;
        if (sec >= 60){
             sec = 0
             min = min + 1;
        }
        $(this).text(pad(min) + ":" + pad(sec)); 

    });
} 

Updated FIDDLE

查看更多
Melony?
3楼-- · 2020-05-07 05:19

Try this code on interval function:

$("#example > tbody tr").each(function(){
    var s = 0; //--- var for not increase 1st td ---
    $("td",this).each(function(){
        var data = $(this).html();
        if(/^[0-9]+\.?[0-9]*$/.test(data)){
          $(this).html(++data);   
        } else {
            if(s == 1) {
              date = new Date();
              var h = date.getHours();
              var m = date.getMinutes();
              if(m < 10) {m = '0'+m;} 
              $(this).html(h+':'+m); 
            };
            s = 1; //--- after 1st td increase ---

      }
   });
});

JSFiddle

查看更多
登录 后发表回答