您好,我无法让我的程序正常运行。我能够清除任何语法错误,但现在我的输出有问题。我需要输出
* * * * *
* * * *
* * *
* *
*
代码是
var i = 1;
while (i < 6)
{
if (i==1)
{
document.getElementById("demo").innerHTML = "* * * * *<br>";
}
else if (i==2)
{
document.getElementById("demo").innerHTML = "* * * *<br>";
}
else if (i==3)
{
document.getElementById("demo").innerHTML = "* * *<br>" ;
}
else if (i==4)
{
document.getElementById("demo").innerHTML = "* *<br>" ;
}
else if (i==5)
{
document.getElementById("demo").innerHTML = "*" ;
}
else
{
document.getElementById("demo").innerHTML = "";
}
i++;
}
答案 0 :(得分:1)
使用
innerHTML += YOUR_VALUE
在现有HTML中插入新的HTML
试试这个:
var i = 1;
while (i < 6) {
if (i == 1) {
document.getElementById("demo").innerHTML += "* * * * *<br>";
} else if (i == 2) {
document.getElementById("demo").innerHTML += " * * * *<br>";
} else if (i == 3) {
document.getElementById("demo").innerHTML += " * * *<br>";
} else if (i == 4) {
document.getElementById("demo").innerHTML += "* * <br>";
} else if (i == 5) {
document.getElementById("demo").innerHTML += "*<br>";
} else {
document.getElementById("demo").innerHTML += "<br>";
}
i++;
}
&#13;
<div id="demo"></div>
&#13;
或者可以简化为:
var i = 5;
var makeStart = function(count) {
var star = '';
for (var i = 0; i < count; i++) {
star += '*';
}
return star;
}
while (i) {
document.getElementById("demo").innerHTML += makeStart(i) + '<br>';
i--;
}
&#13;
<div id="demo"></div>
&#13;
答案 1 :(得分:0)
您可以改用循环。
(function(){
var html = "";
for(var i = 5; i>0; i--){
for(var j=0; j<i; j++){
html+= "* ";
}
html += "<br/>";
}
document.getElementById("demo").innerHTML= html;
})()
<div id="demo"></div>