簡體   English   中英

動態添加 <td> 到桌子

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

我正在嘗試創建一個從今天開始的30天日期的表格。

現在我有這個工作,但它作為字符串返回。

我想添加一個<td>並將每個日期返回到我的表中。

我的代碼是這樣

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

這應該工作:

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

盡量不要每次都附加到DOM,這會使它變慢且效率低下,尤其是當您要附加的項目過多時。 而是將它們加起來並附加到最​​后。

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

演示

您可以隨時添加它們。 像這樣

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);
}

或者,為了更快地運行,請先構建您的元素,然后在末尾添加一次。

只需對現有代碼進行一些補充,請參見下文,

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>');

演示: http : //jsfiddle.net/wzdr2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM