如何在html textarea中循环循环打印javascript?

时间:2019-07-17 09:33:23

标签: javascript

当输入为2时,打印'2 x 10 = 20',但不打印整个表格。我尝试了各种方法。但是结果是一样的。

没有错误。就像打印整个乘法表一样。

function loop() {
  var i = 1;
  var x = document.getElementById("num").value;

  //document.getElementById("result").value = result;

  while (i <= 10) {

    document.getElementById("result").value = x + " x " + i + " = " + i * x;
    i++;
  }
}
<h1>While loop: </h1>
<p>The while loop keeps repeating an action until an associated condition returns false.</p>
<img src="images/loop.jpg" /><br/>
<img src="images/loop2.jpg" /><br/>

<body>
  <p>JavaScripts Runs:</p>
  <script src="while_1loop.js">
  </script><br/> What number table would you like to have?<input type="number" name="" id="num" /><br>
  <button type="button" onclick="loop()" ;>Start</button><br>
  <textarea rows="12" cols="15" id="result" readonly>
       
              </textarea><br/>

2 个答案:

答案 0 :(得分:1)

您总是在更改'结果'的值,而不是添加它:

function loop() {
  var i = 1;
  var x = document.getElementById("num").value;

  //document.getElementById("result").value = result;

  while (i <= 10) {

    var result = document.getElementById("result");
    var sum = document.createTextNode(x + " x " + i + " = " + i * x + "\n");

    result.appendChild(sum);
    i++;
  }
}
<h1>While loop: </h1>
<p>The while loop keeps repeating an action until an associated condition returns false.</p>
<img src="images/loop.jpg" /><br/>
<img src="images/loop2.jpg" /><br/>

<body>
  <p>JavaScripts Runs:</p>
  <script src="while_1loop.js">
  </script><br/> What number table would you like to have?<input type="number" name="" id="num" /><br>
  <button type="button" onclick="loop()" ;>Start</button><br>
  <textarea rows="12" cols="15" id="result" readonly>
       
              </textarea><br/>

答案 1 :(得分:-1)

如果我明白你的意思,

您可以使用以下代码重写整个文本区域:

document.getElementById("result").value = x + " x " + i + " = " + i * x;

,但是您需要在较旧的结果之后添加新的结果。像这样:

var oldValue = document.getElementById("result").value;
var result = x + " x " + i + " = " + i * x;
document.getElementById("result").value = oldValue + '\n' + result;