美好的一天 我有一些代码,我希望使用javascripts渲染菱形数字 它在1 onclick上使用了2个javascript函数, 但不知何故,其他功能似乎无法正常工作
这是代码的html标记
<html>
<head>
<script src="pyramid.js"></script>
</head>
<body>
<center>
<table>
<tr><td>Enter a number</td><td><input type="text" id="no" class="nomor" name="number"></td></tr>
<tr><td></td><td><input type=submit value="submit" id="pattern" onclick="Pyramid(document.getElementById('no').value);Pyramiddn(document.getElementById('no').value);"></td></tr>
</body>
</html>
这里是javascript标记
function Pyramid(number)
{
document.write("<center>"); // this to align the output in center
if(number>0)
{
Pyramid(number-1); //this is to move through the number of iterations
for(j=1;j<=number;j++) //this loop is to print the numbers in ascending order
{
document.write(" "+j);
}
for(k=number-1;k>0;k--) // this loop is to print the numbers in descending order
{
document.write(" "+k);
}
}
document.write("<br>");
} ;
function Pyramiddn(number)
{
document.write("<center>"); // this to align the output in center
if(number>0)
{
//this is to move through the number of iterations
for(i=1;i<=number;i++) //this loop is to print the numbers in ascending order
{
document.write(" "+i);
}
for(l=number-1;l>0;l--) // this loop is to print the numbers in descending order
{
document.write(" "+l);
}
Pyramiddn(number-1);
}
document.write("<br>");
} ;
期望的结果是从这两个函数(如
)创建菱形数字 1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 3 2 1
1 2 3 2 1
1 2 1
1
答案 0 :(得分:0)
相反,两个函数,两个调用,document.write()
你可以使用一个函数,一个调用,构建字符串并将字符串放在容器中,如下所示:
function diamond(number) {
line='';
//up
for(i=1;i<=number;i++) {
for(j=1;j<=i;j++) {
line+=' '+j; //left
}
for(j=i;j>1;j--) {
line+=' '+(j-1); //right
}
line+='<br>';
}
//down
for(i=number-1;i>=1;i--) {
for(j=1;j<=i;j++) {
line+=' '+j; //left
}
for(j=i;j>1;j--) {
line+=' '+(j-1); //right
}
line+='<br>';
}
document.getElementById('result').innerHTML=line;
}
演示:
function diamond(number) {
line='';
//up
for(i=1;i<=number;i++) {
for(j=1;j<=i;j++) {
line+=' '+j; //left
}
for(j=i;j>1;j--) {
line+=' '+(j-1); //right
}
line+='<br>';
}
//down
for(i=number-1;i>=1;i--) {
for(j=1;j<=i;j++) {
line+=' '+j; //left
}
for(j=i;j>1;j--) {
line+=' '+(j-1); //right
}
line+='<br>';
}
document.getElementById('result').innerHTML=line;
}
&#13;
#result {
text-align:center;
}
&#13;
<table>
<tr><td>Enter a number</td><td><input type="text" id="no" class="nomor" name="number"></td></tr>
<tr><td></td><td><input type=submit value="submit" id="pattern" onclick="diamond(document.getElementById('no').value);"></td></tr>
</table>
<div id="result">
</div>
&#13;
此外,相反旧的和不推荐使用的中心标记,您应该使用CSS集中结果html:
#result {
text-align:center;
}