简体   繁体   English

动态添加 <td> 到桌子

[英]Dynamically add <td>'s to a table

I am trying to create a table of 30 days of dates, starting from today. 我正在尝试创建一个从今天开始的30天日期的表格。

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. 我想添加一个<td>并将每个日期返回到我的表中。

My code is this 我的代码是这样

HTML HTML

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

</tbody>
</table>

JS 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 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. 尽量不要每次都附加到DOM,这会使它变慢且效率低下,尤其是当您要附加的项目过多时。 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/ 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/ 演示: http : //jsfiddle.net/wzdr2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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