如何在函数中插入while循环

我试图在名为 myFunction 的函数中插入 while 循环。当您单击该按钮时,它应该显示数组结果。


<!DOCTYPE html>

<html>

<body>

<button id="btn">Click Me!</button>


<p id="i"><strong>this</strong> represents:</p>


<p id="demo"></p>

<script>


  function myFunction () {

let i = 0;

while(i<5){

    document.write(i  + '<br/>');

    i++;

}

}


var btn = document.getElementById("btn");

btn.addEventListener("click", myFunction());



</script>

</body>

</html>


繁星淼淼
浏览 88回答 2
2回答

慕田峪9158850

尝试这样:<!DOCTYPE html><html>&nbsp; <body>&nbsp; &nbsp; <button id="btn">Click Me!</button>&nbsp; &nbsp; <p id="i"><strong>this</strong> represents:</p>&nbsp; &nbsp; <p id="demo"></p>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; function myFunction() {&nbsp; &nbsp; &nbsp; &nbsp; console.log(1)&nbsp; &nbsp; &nbsp; &nbsp; let i = 0;&nbsp; &nbsp; &nbsp; &nbsp; while (i < 5) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.write(i + '<br/>');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; var btn = document.getElementById("btn");&nbsp; &nbsp; &nbsp; btn.addEventListener("click", myFunction);&nbsp; &nbsp; </script>&nbsp; </body></html>有一些小错误需要纠正,例如was()应该是以及函数名称后面所需括号myFunction的定义。myFunction()

慕哥9229398

myFunction 之后缺少 ():&nbsp; function myFunction() {let i = 0;while(i<5){&nbsp; &nbsp; document.write(i&nbsp; + '<br/>');&nbsp; &nbsp; i++;}}&nbsp;您确定要使用document.write而不是console.log(i)?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript