以下代码是我的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代码
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 ="  ";
}
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="  ";
for ( var i = 0; i < no3 + 1; i++) {
for ( var index = 0; index <= i; index++) {
document.getElementById("p").innerHTML = "  ";
}
for ( var index2 = 0; index2 < (no4 * 2) - 3; index2++) {
document.getElementById("p").innerHTML = "*";
}
no4 = no4 - 1;
document.getElementById("p").innerHTML = "</br> ";
}
}
我想打印菱形结构的图案。当我使用document.write而不是document.getElementById(“p”)。innerHTML进行一些修改时,上面的程序正在工作。有什么错误我没有得到它。< / p>
答案 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 +="  ";
}
no2 = no2 - 1;
for ( var index2 = 0; index2 < (i * 2) + 1; index2++) {
diamond += "*";
}
diamond+="</br>";
}
diamond+="  ";
for ( var i = 0; i < no3 + 1; i++) {
for ( var index = 0; index <= i; index++) {
diamond += "  ";
}
for ( var index2 = 0; index2 < (no4 * 2) - 3; index2++) {
diamond += "*";
}
no4 = no4 - 1;
diamond += "</br> ";
}
document.getElementById("p").innerHTML = diamond;
}
工作示例 - http://jsfiddle.net/fdadE/
答案 1 :(得分:1)
你没有附加你想要的东西,只是分配。将所有=
替换为+=
,如下所示:
document.getElementById("p").innerHTML = "  ";
到
document.getElementById("p").innerHTML += "  ";