我有两个想法克服这一点。首先是创建元素,改变其风格,并追加它。
<script type="text/javascript">
for (var i = 0; i < 5; i++) {
var div = document.createElement("div");
div.style.width = "200px";
div.style.backgroundColor = "yellow";
document.appendChild(div);
}
</script>
另一个想法是,你不需要对DOM元素的引用,因为你只是改变样式,所以你可以将样式应用于CSS。例如:
<style type="text/css">
div.something {
width: 200px;
background-color: yellow;
}
</style>
<script type="text/javascript">
for (var i = 0; i < 5; i++) {
document.write("<div class='something'>text</div>");
// Or use the createElement/appendChild approach from above,
// where you'd need to set the div.className property as "something"
}
</script>
来源
2013-06-05 21:06:28
Ian
这可能有助于http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice。此外,你忘了声明'我'。 – elclanrs
id是唯一的,您应该使用name属性并使用getElementsByName() – Saturnix