简体   繁体   中英

Dynamically add <td>'s to a table

I am trying to create a table of 30 days of dates, starting from today.

right now I have this working, but it is being returned as a string.

I want to add a <td> with each date returned to my table.

My code is this

HTML

<table>
<tbody>
    <tr>
        <td></td> <!-- Add Each Date here -->
    </tr>

</tbody>
</table>

JS

var date = moment(),
    begin = moment(date).startOf('week').isoWeekday(1);

var str = "";
for (var i=0; i<30; i++) {
    str += begin.format("MMM Do") + '<br>';
    begin.add('days', 1);
}

// Would like to add date to each <td> and add <td> to the table
document.body.innerHTML = str;

DEMO

This should work:

for (var i=0; i<30; i++) {
    $("table tr").append("<td>" + begin.format("MMM Do") + "</td>");
    begin.add('days', 1);
}

Try not to append to DOM each time, it'l make it slower and inefficient especially if you have too many items to be appended. Instead add them up and append in the end.

var str = "", $tds= [];
for (var i=0; i<30; i++) {
    $tds.push('<td>' + begin.format("MMM Do") + '</td>'); //push the tds to the temp array
    begin.add('days', 1);
}

// Would like to add date to each <td> and add <td> to the table
$('table tr').append($tds); //append in the end

Demo

You could append them as you go. Like so...

http://jsfiddle.net/jzKMS/

for (var i=0; i<30; i++) {
    $('#dates tbody').append('<tr><td>' + begin.format("MMM Do") + '</td></tr>');
    begin.add('days', 1);
}

Or, for faster running, build your elements first and append once at the end.

Just need slight addition to your existing code see below,

var date = moment(),
    begin = moment(date).startOf('week').isoWeekday(1);

var str = [];
for (var i=0; i<30; i++) {
    str.push('<td>' + begin.format("MMM Do") + '</td>');
    begin.add('days', 1);
}

$('#myTable tbody').append('<tr>' + str.join('') + '</tr>');

DEMO: http://jsfiddle.net/wzdr2/

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