简体   繁体   中英

how do i append in this function?

i have this code:

for (var i = 0; i < data.times.length; ++i) {
    var time = formatTime(data.times[i].time);
    tableContent += '<tr><td>' + data.times[i].destination.name + '</td><td id="appendLate' + i + '">' + time + '</td><td>' + data.times[i].track + '</td><td>' + data.times[i].train_type + '</td><td>' + data.times[i].company + '</td></tr>'
    // laat vertragingen zien (BETA)
    if (data.times[i].delay / 60 >= 1) {
        $('#appendLate' + i + '').append("+" + data.times[i].delay / 60).addClass("late");
    }
}
table.html(tableContent);
}

The if statement appends stuff and adds a class. i know it wont work like this.. but i cant seem to get how it WIL work.. Can some one help?

See it live: http://codepen.io/shiva112/pen/JGXoVJ?editors=001

Well, you're basically almost there. The right way to do it is to build the entire string before doing any DOM manipulation, since DOM operations are very slow (relatively).

Let's say your index.html looks like:

<html>
<head>
  <title>Cool site!</title>
</head>
<body>
  <table id="myCoolTable"></table>
</body>
</html>

Then your JavaScript simply becomes:

var tableContent = '';
for (var i = 0; i < data.times.length; ++i) {
  var time = formatTime(data.times[i].time);

  tableContent += '<tr>'
                    + '<td>' + data.times[i].destination.name + '</td>';

  if (data.times[i].delay / 60 >= 1) {
    tableContent += '<td id=\'appendLate\'' + i + ' class=\'late\'>' + time + '</td>' + '+' + (data.times[i].delay / 60);
  } else {
    tableContent += '<td id=\'appendLate\'' + i + '>' + time + '</td>';
  }

  tableContent += '<td id=\'appendLate\'' + i + '>' + time + '</td>'
                + '<td>' + data.times[i].track + '</td>'
                + '<td>' + data.times[i].train_type + '</td>'
                + '<td>' + data.times[i].company + '</td>'
                + '</tr>';
}

$('#myCoolTable').html(tableContent);

What this does is build the HTML for the entire table. Then update the table only once. Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM