admin管理员组

文章数量:1328556

In server side, I emit last 10 rows of my database in every 3 second;

setInterval(function() {
              connection.query("SELECT * FROM report ORDER BY id DESC limit 10", function(err, rows) {
                if (err) console.log(err);
                else {
                  console.log("Last 10 record emitted.");
                //  console.log("rows: " + JSON.stringify(rows, null, 3));
                  io.emit("last_list", rows)
                }
              });
            }, 3000);

In client side, I append these rows to table;

  socket.on('last_list', function(rows) {
    for (var i = 0; i < rows.length; i++) {
      var row = rows[i];

      $('#myTable').append('<tr><td>' + row.id + '</td><td>' + row.fabrika + '</td><td>' +
      row.kumes + '</td><td>' + row.makina + '</td><td>' + row.kat + '</td><td>' +
      row.sol_sag + '</td><td style="color: rgba(25, 44, 44, 1); font-weight: bolder;">' +
      row.adet + '</td></tr>');

    }
  });

My question is, how can I update table instead of add new rows every 3 seconds?

In server side, I emit last 10 rows of my database in every 3 second;

setInterval(function() {
              connection.query("SELECT * FROM report ORDER BY id DESC limit 10", function(err, rows) {
                if (err) console.log(err);
                else {
                  console.log("Last 10 record emitted.");
                //  console.log("rows: " + JSON.stringify(rows, null, 3));
                  io.emit("last_list", rows)
                }
              });
            }, 3000);

In client side, I append these rows to table;

  socket.on('last_list', function(rows) {
    for (var i = 0; i < rows.length; i++) {
      var row = rows[i];

      $('#myTable').append('<tr><td>' + row.id + '</td><td>' + row.fabrika + '</td><td>' +
      row.kumes + '</td><td>' + row.makina + '</td><td>' + row.kat + '</td><td>' +
      row.sol_sag + '</td><td style="color: rgba(25, 44, 44, 1); font-weight: bolder;">' +
      row.adet + '</td></tr>');

    }
  });

My question is, how can I update table instead of add new rows every 3 seconds?

Share Improve this question asked Aug 13, 2017 at 11:58 ilvthsgmilvthsgm 6361 gold badge10 silver badges30 bronze badges 5
  • What's the difference between adding new rows and updating table ? – Anurag Singh Bisht Commented Aug 13, 2017 at 12:09
  • 1 Does that mean you want to clear the table and re-load the whole data? – Imran Arshad Commented Aug 13, 2017 at 12:11
  • @user1041953 This is exactly what I'm trying to achieve. – ilvthsgm Commented Aug 13, 2017 at 12:12
  • 1 @erayaras but your current approach is much better than clearing the table every time. It may get the browser stuck in devices with low-CPU power. – webgodo Commented Aug 13, 2017 at 12:36
  • 1 Anyway, it's better to use a template-engine like Mustache.js in order to get rid of inline-HTML in the JS code. – webgodo Commented Aug 13, 2017 at 12:38
Add a ment  | 

4 Answers 4

Reset to default 3
$('#myTable').empty();

Just add above list as the first line of your callback function i.e.:

socket.on('last_list', function(rows) {
  $('#myTable').empty();
  //REST OF YOUR CODE AS IS HERE...
});

FYI: Just for better performance, don't change the DOM with every loop. Instead keep adding rows to a variable and than assign that to your table after the loop. DOM operations are expensive than variables.

Clear the table body every time before append. You can either give your tbody an ID and clear it like $("#tbody").html("") or you can use the following way.

socket.on('last_list', function(rows) {
$('#myTable tbody').html("");
for (var i = 0; i < rows.length; i++) {
  var row = rows[i];



  $('#myTable').append('<tr><td>' + row.id + '</td><td>' + row.fabrika + '</td><td>' +
  row.kumes + '</td><td>' + row.makina + '</td><td>' + row.kat + '</td><td>' +
  row.sol_sag + '</td><td style="color: rgba(25, 44, 44, 1); font-weight: bolder;">' +
  row.adet + '</td></tr>');

}

});

You can use $().empty to clear the content of table and then use $().append or $().html to put the html content.

Also instead of using string and concatenating each variable, you can make use of template string i.e backticks to create mutliline html content more conveniently.

function generateTable(row) {

  return `
      <tr>
        <td>${row.id}</td>
        <td>${row.fabrika}</td>
        <td>${row.kumes}</td>
        <td>${row.makina}</td>
        <td>${row.kat}</td>
        <td>${row.sol_sag}</td>
        <td style="color: rgba(25, 44, 44, 1); font-weight: bolder;">${row.adet}</td>
       </tr>
     `
}

var rows = [{
  id: '1',
  fabrika: '2',
  kumes: '3',
  makina: '4',
  kat: '5',
  sol_sag: '6',
  adet: '7'
}, {
  id: '2',
  fabrika: '3',
  kumes: '4',
  makina: '5',
  kat: '6',
  sol_sag: '7',
  adet: '8'
}]

setTimeout(() => {
  $('table').empty();
  $('table').append(generateTable(rows[0]));
}, 1000)

setTimeout(() => {
  $('table').empty();
  $('table').append(generateTable(rows[1]));
}, 1000)
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
</table>

Keep your data in the array. Every time new data es append it to the array and re-render your array with updated dataset. Like this:

var data = []
var tableContainer = $('#myTable')

function renderTable() {
  tableContainer.innerHTML = data.map(function(row) {
    return '<tr><td>' + row.id + '</td><td>' + row.fabrika + '</td><td>' +
      row.kumes + '</td><td>' + row.makina + '</td><td>' + row.kat + '</td><td>' +
      row.sol_sag + '</td><td style="color: rgba(25, 44, 44, 1); font-weight: bolder;">' +
      row.adet + '</td></tr>'
  }).join('')
}

function updateData(newData) {
  newData.forEach(function(item) {
    data.push(item)
  })
}

socket.on('last_list', function(rows) {
  updateData(rows)
  renderTable()
});

本文标签: javascriptUpdate Table with jQueryStack Overflow