我的代码(html / javascript)在这里允许用户输入方块的大小和颜色。问题是当我单击go按钮时,textfields消失,包括按钮,显示的是输出。有没有什么方法可以保留文本字段和按钮,然后输出它下方的方块?
<html>
<head>
<script type="text/javascript">
size=0;
function display(form){
size=form.inputbox.value;
color=form.inputbox2.value;
for(i=0;i<size;i++){
for(j=0;j<size;j++){
if(i==0||i==(size-1)){
document.write("<font color="+color+">* ");
}
else if (j == 0||j == (size-1)) {
document.write("* ");
}
else {
document.write(" ");
}
}
document.write("<br>");
}
}
</script>
</head>
<body>
<form name="form1" action="" method="get">
Input size of the square:
<input type="text" name="inputbox" value=""><br>
Input color of the square:
<input type="text" name="inputbox2" value="">
<input type="button" name="button" value="Go" onClick="display(this.form)">
</form>
</body>
</html>
答案 0 :(得分:4)
在已完成渲染的页面上调用document.write
将破坏页面上现有的DOM文档,仅用新编写的HTML元素替换它。
如果您希望添加到现有DOM元素,请选择一个元素并写入其innerHTML
属性。
<html>
<head>
<script type="text/javascript">
size=0;
function display(form){
size=form.inputbox.value;
color=form.inputbox2.value;
// A node to write into
writeTo = document.getElementById('writeTo');
for(i=0;i<size;i++){
for(j=0;j<size;j++){
if(i==0||i==(size-1)){
writeTo.innerHTML = writeTo.innerHTML + "<font color="+color+">* ";
}
else if (j == 0||j == (size-1)) {
writeTo.innerHTML = writeTo.innerHTML + "* ";
}
else {
writeTo.innerHTML = writeTo.innerHTML + " ";
}
}
writeTo.innerHTML = writeTo.innerHTML + "<br>";
}
}
</script>
</head>
<body>
<form name="form1" action="" method="get">
Input size of the square:
<input type="text" name="inputbox" value=""><br>
Input color of the square:
<input type="text" name="inputbox2" value="">
<input type="button" name="button" value="Go" onClick="display(this.form)">
</form>
<div id='writeTo'></div>
</body>
</html>
在HTML中添加一个空节点,例如:
<div id='writeTo'></div>
Here it is in action on jsFiddle.net
要使方块成为所有正确的颜色,最简单的方法是更改<div id='writeTo'>
document.getElementById('writeTo').style.color = color;