[英]Creating a table with document.write in javascript
I seem to get nothing when I run my code, my code is supposed to create a 10 by 10 table.当我运行我的代码时,我似乎什么也没得到,我的代码应该创建一个 10 x 10 的表。 I am supposed to make it while using this form .
我应该在使用这个表格时做到这一点。 And it is also supposed to use a for loop so that I dont have to repeat myself like 100 times.
它也应该使用 for 循环,这样我就不必重复 100 次。
document.write("<table>")
document.write("<td>......")
document.write("</table>")
This is my current code that I need to improve.这是我当前需要改进的代码。
<script>
var table = " ";
var rows = 10;
var cols = 10;
for (var r= 0; r < rows;r++)
{
table += "<tr>";
for(var c = 1; c <= cols; c++)
{
table += "<td>" + c + "</td>";
}
table += "</td>";
}
document.write("<table border=1>" + table + "</table>");
}
</script>
Your code is faulty because you have an invalid curly brace at the end and you never end your first <tr>
.你的代码有问题,因为你在最后有一个无效的花括号,你永远不会结束你的第一个
<tr>
。
Here is a corrected version of your code:这是您的代码的更正版本:
var table = " ";
var rows = 10;
var cols = 10;
for (var r= 0; r < rows;r++)
{
table += "<tr>";
for(var c = 1; c <= cols; c++)
{
table += "<td>" + c + "</td>";
}
table += "</tr>";
}
document.write("<table border=1>" + table + "</table>");
I changed the line我换了线
table += "</td>"
to:到:
table += "</tr>"
and I removed the curly brace at the end.最后我去掉了花括号。
Here is a working example of the code, https://jsfiddle.net/h2qf9aj4/这是代码的一个工作示例, https://jsfiddle.net/h2qf9aj4/
document.write() actually deletes everything then writes the text on the inside. document.write() 实际上会删除所有内容,然后在里面写入文本。 So what you are doing is writing a page, deleting and writing something different, then writing another something...
所以你正在做的是写一个页面,删除和写一些不同的东西,然后写另一个东西......
What you can do is append by doing你可以做的是通过做附加
document.getElementByTagName('body')[0].innerHTML += "<table>"
to create something at the end of the inner HTML body tag在内部 HTML body 标签的末尾创建一些东西
Here's an alternative to document.write and concatenation:这是 document.write 和串联的替代方法:
<script>
var table = document.createElement("table");
var rows = 10;
var cols = 10;
for(var r = 0; r < rows; r++){
var row_create = document.createElement("tr");
for(var c = 0; c < cols; c++){
var col_create = document.createElement("td");
row_create.appendChild(col_create);
}
table.appendChild(row_create);
}
document.body.appendChild(table);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.