为什么单击Go按钮后文本字段和按钮会消失

Why does the textfields and button disappears after clicking the Go button?

本文关键字:按钮 消失 字段 单击 Go 为什么 文本      更新时间:2023-09-26

我在这里有我的代码(html/javascript),它允许用户输入正方形的大小和颜色。问题是当我点击go按钮时,文本字段会消失,包括按钮,显示的是输出。有没有什么方法可以让我保留文本字段和按钮,然后输出它下面的方块?


<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+">*&nbsp;");
                    }
                else if (j == 0||j == (size-1)) {
                        document.write("*&nbsp;");
                    }
                else {
                        document.write("&nbsp;&nbsp;&nbsp;");
                    }
            }
                    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>

在已完成渲染的页面上调用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+">*&nbsp;";
                    }
                else if (j == 0||j == (size-1)) {
                        writeTo.innerHTML = writeTo.innerHTML + "*&nbsp;";
                    }
                else {
                        writeTo.innerHTML = writeTo.innerHTML + "&nbsp;&nbsp;&nbsp;";
                    }
            }
                    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>

这是在jsFiddle.net 上运行的

要使正方形都是正确的颜色,最简单的方法是更改<div id='writeTo'> 的CSS颜色属性

document.getElementById('writeTo').style.color = color;