将结果显示在textarea中作为日志

时间:2019-01-18 20:52:14

标签: javascript

我需要在文本区域中以日志形式显示功能的结果。

显示的代码可以在文本区域中使用,但是如果我们按下另一个功能,它将覆盖前一个功能,那么我需要同时显示它们和执行的最新功能。

<!DOCTYPE html>
<html>
  <body>

    <!-- If you click on 'myFunction()' and then on 'myFunction2()' the result would be:
    
    Function2
    Function1
    
    -->    
    
    <textarea id="myTextarea"></textarea>
    
    <br>

    <button type="button" onclick="myFunction()">Try it</button>
    <button type="button" onclick="myFunction2()">Try it</button>

    <script>

      function myFunction() {
        var x = "Function1";
        document.getElementById("myTextarea").innerHTML = x;
      }

      function myFunction2() {
        var z = "Function2";
        document.getElementById("myTextarea").innerHTML = z;
      }

    </script>

  </body>
</html>

3 个答案:

答案 0 :(得分:2)

在文本中添加\n,并在值后附加+=,而不用=

覆盖

<!DOCTYPE html>
<html>
  <body>

    <!-- If you click on 'myFunction()' and then on 'myFunction2()' the result would be:
    
    Function2
    Function1
    
    -->    
    
    <textarea id="myTextarea"></textarea>
    
    <br>

    <button type="button" onclick="myFunction()">Try it</button>
    <button type="button" onclick="myFunction2()">Try it</button>

    <script>

      function myFunction() {
        var x = "Function1";
        document.getElementById("myTextarea").innerHTML = `${x}\n${document.getElementById("myTextarea").innerHTML}`;
      }

      function myFunction2() {
        var z = "Function2";
        document.getElementById("myTextarea").innerHTML = `${z}\n${document.getElementById("myTextarea").innerHTML}`;
      }

    </script>

  </body>
</html>

答案 1 :(得分:1)

您每次都覆盖文本区域。相反,只需将其附加到“日志”中即可。您可以使用\n字符(JavaScript string newline character?)强制日志消息打印到新行

<!DOCTYPE html>
<html>
  <body>

    <!-- If you click on 'myFunction()' and then on 'myFunction2()' the result would be:
    
    Function2
    Function1
    
    -->    
    
    <textarea id="myTextarea"></textarea>
    
    <br>

    <button type="button" onclick="myFunction()">Try it</button>
    <button type="button" onclick="myFunction2()">Try it</button>

    <script>
      function addLogMessage(message) {
        const textArea = document.getElementById("myTextarea");
        textArea.innerHTML += `${message} \n`;
      }

      function myFunction() {
        var x = "Function1";
        addLogMessage(x);
      }

      function myFunction2() {
        var z = "Function2";
        addLogMessage(z);
      }
      
      

    </script>

  </body>
</html>

答案 2 :(得分:0)

您分配时未存储文本区域的先前值。先前的解决方案会附加数据,我相信您已经要求将其添加

@BeforeClass

希望这会有所帮助!