用for循环创建表

时间:2019-08-14 13:09:52

标签: javascript

我尝试使用for循环重写此代码,但是代码行显示不正确,我在做什么错了?

https://jsfiddle.net/tsnL87jk/1/

var table = "<table border='1' width='100%' height='300px'>";
var tr=1;
while(tr<=10){
    table+="<tr>";
    var td=1;
    while(td<=10){
        var x = tr * td;
        if(td%2==0)
            table+="<td style='background-color:red;'>"+x+"</td>";
        else
            table+="<td style='background-color:green;'>"+x+"</td>";
        td++;
    }
    table+="</tr>";
    tr++;
}
table+="</table>";

document.write(table);

var table = "<table border='1' width='100%' height='300px'>";
var tr = 1;

for (tr=1; tr <= 10; tr++) {
    table += "<tr>";

    for ( var td=1; td <= 10; td++) {
        var x = tr * td;
        if (td % 2 == 0) {
            table += "<td style='background-color:red;'>" + x + "</td>";
        } else {
            table += "<td style='background-color:green;'>" + x + "</td>";
        }
    }
    table+="</tr>";
}

table += "</table>";
document.write(table);

https://jsfiddle.net/7x5h6k2z/

1 个答案:

答案 0 :(得分:0)

如果要链接的小提琴无所不能,那么第一个for循环应该是...

for (tr=1; tr <= 100; tr++)