0

下面的代码是我的html代码

星号.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="CssText.css">
</head>
<body>
    <form>
        Enter number of rows: <input type="text" name="t1" /> <input
            type="button" value="Display Diomond"
            onclick="return myFunction(this.form)" />
    </form>

<p id="p"></p>
<script src="StarPrint.js"></script>
</body>
</html>

下面的代码是我的 javascript 代码

StarPrint.js

function myFunction(form) {
    var no;
    no = form.t1.value;
    no = no / 2;
    var no2 = no;
    var no3 = no;
    var no4 = no;
    var no5 = no;
    var no6 = no;

    for ( var i = 0; i < no; i++) {
        for ( var index = 0; index < no2; index++) {
            document.getElementById("p").innerHTML ="&nbsp&nbsp";
        }
        no2 = no2 - 1;

        for ( var index2 = 0; index2 < (i * 2) + 1; index2++) {
            document.getElementById("p").innerHTML = "*";
        }
        document.getElementById("p").innerHTML="</br>";
    }
    document.getElementById("p").innerHTML="&nbsp&nbsp";
    for ( var i = 0; i < no3 + 1; i++) {

        for ( var index = 0; index <= i; index++) {
            document.getElementById("p").innerHTML = "&nbsp&nbsp";
        }
        for ( var index2 = 0; index2 < (no4 * 2) - 3; index2++) {
            document.getElementById("p").innerHTML = "*";
        }
        no4 = no4 - 1;
        document.getElementById("p").innerHTML = "</br>&nbsp";
    }

}

我想打印菱形结构的图案。当我使用 document.write 而不是 document.getElementById("p").innerHTML 并进行一些修改时,上述程序正在运行。我没有得到它的错误在哪里。

4

2 回答 2

2

您正在替换p每次调用的内容document.getElementById("p").innerHTML =

相反,将文本保存到变量中并仅p在最后分配给它:

function myFunction(form) {
    var no;
    no = form.t1.value;
    no = no / 2;
    var no2 = no;
    var no3 = no;
    var no4 = no;
    var no5 = no;
    var no6 = no;
    var diamond = "";
    for ( var i = 0; i < no; i++) {
        for ( var index = 0; index < no2; index++) {
            diamond +="&nbsp&nbsp";
        }
        no2 = no2 - 1;

        for ( var index2 = 0; index2 < (i * 2) + 1; index2++) {
            diamond += "*";
        }
        diamond+="</br>";
    }
    diamond+="&nbsp&nbsp";
    for ( var i = 0; i < no3 + 1; i++) {

        for ( var index = 0; index <= i; index++) {
            diamond += "&nbsp&nbsp";
        }
        for ( var index2 = 0; index2 < (no4 * 2) - 3; index2++) {
            diamond += "*";
        }
        no4 = no4 - 1;
        diamond  += "</br>&nbsp";
    }
    document.getElementById("p").innerHTML = diamond;
}

工作示例 - http://jsfiddle.net/fdadE/

于 2013-10-04T13:06:06.603 回答
1

你没有附加你想要的东西,而只是分配。全部替换=+=如下所示:

document.getElementById("p").innerHTML = "&nbsp&nbsp";

document.getElementById("p").innerHTML += "&nbsp&nbsp";
于 2013-10-04T13:03:44.007 回答