[英]How to print javascript while loop result in html textarea?
當輸入為 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/>
您總是在更改“結果”的值,而不是添加它:
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/>
如果我明白你的意思,
您可以使用以下代碼重寫整個 textarea:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.