没有输出显示

时间:2013-10-04 13:00:27

标签: javascript html

以下代码是我的HTML代码

Star.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进行一些修改时,上面的程序正在工作。有什么错误我没有得到它。< / p>

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分:1)

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

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

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