我试图在单击按钮后打印6个随机数。然后,每次我再次单击该按钮时,随机数应从新行开始,但是我不知道该怎么做。我尝试了一切,但没有任何效果。感谢您的帮助。



        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>

最佳答案

无法100%清楚地知道要在何处使用换行符,但是在文本区域中,换行符为\n。如果这在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>

09-20 06:44