嘿那里,寻找解决方案

时间:2016-03-01 06:30:13

标签: javascript

您好,我无法让我的程序正常运行。我能够清除任何语法错误,但现在我的输出有问题。我需要输出

* * * * *
* * * * 
* * *
* * 
*

代码是

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++;
}

2 个答案:

答案 0 :(得分:1)

  

使用innerHTML += YOUR_VALUE在现有HTML中插入新的HTML

试试这个:

&#13;
&#13;
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;
&#13;
&#13;

Fiddle here

或者可以简化为:

&#13;
&#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;
&#13;
&#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>