[英]JS - How to start from new line inside for loop?
I am trying to print 6 random numbers after clicking a button. 我点击按钮后试图打印6个随机数字。 Then every time I click the button again, random numbers should start from new line however I do not know how.
然后,每次我再次单击该按钮时,随机数应该从新行开始,但我不知道如何。 I tried everything and nothing works.
我尝试了一切,没有任何作用。 I appreciate any help.
我感谢任何帮助。
function fname() { for(i=1; i<=6; i++) { number = number + Math.floor(Math.random() * 47 + 1) + "-"; var print = number + " GOOD LUCK!"; } document.getElementById("total").value = print; }
<!DOCTYPE html> <html> <head> <title>Let's ROLL!</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> input, button {display: block;} </style> <script> var number = ""; function fname() { for(i=1; i<=6; i++) { number = number + Math.floor(Math.random() * 47 + 1) + "-"; var print = number + " GOOD LUCK!"; } document.getElementById("total").value = print; } </script> </head> <body> <div> <button onclick="fname()">ROLL!</button> <textarea id="total" rows="12" cols="50" readonly></textarea> </div> </body> </html>
Not 100% clear on where you wanted the breaks, but in a text area, a line break is \\n
. 不是100%清楚你想要休息的地方,但在文本区域,换行符是
\\n
。 If this was in an HTML element, you would use <br />
. 如果这是在HTML元素中,您将使用
<br />
。
var number = ""; function fname() { for (i = 1; i <= 6; i++) { number = number + Math.floor(Math.random() * 47 + 1) + "-"; } number = number + "\\n"; var print = number + "GOOD LUCK!"; document.getElementById("total").value = print; }
input, button { display: block; }
<div> <button onclick="fname()">ROLL!</button> <textarea id="total" rows="12" cols="50" readonly></textarea> </div>
Add "\\n". 添加“\\ n”。
I am assuming you want to concatenate the new text in the text area, so you should use += instead of =: 我假设您要在文本区域中连接新文本,因此您应该使用+ =而不是=:
document.getElementById("total").value += print + "\n";
You can use arrays and .join()
the numbers and lines together by their appropriate delimiters. 您可以通过适当的分隔符将数组和
.join()
数字和行一起使用。 This only inserts the characters between the elements. 这仅在元素之间插入字符。
\\n
in a string renders a new line. \\n
在字符串中呈现新行。
var button = document.getElementById('roll'); var total = document.getElementById('total'); var rolls = []; button.onclick = function() { var roll = []; for(var i=0; i<6; ++i) roll.push(Math.floor(Math.random() * 47 + 1)); rolls.push(roll.join('-')); total.value = rolls.join('\\n') + "\\nGOOD LUCK!"; }
<button id="roll">ROLL!</button><br> <textarea id="total" rows="12" cols="50" readonly></textarea>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.