【问题标题】:How can I get both outputs?如何获得两个输出?
【发布时间】:2019-10-24 05:34:18
【问题描述】:

我正在使用document.write() 运行一些基本的测试用例,它会删除所有现有的 HTML,在 head 标记中。只有当我将脚本放在<body> 标记中时,才能获得所需的输出。

在正文中成功运行脚本。但是脚本在<head> 标签中使用时会导致问题。

<html>
<head>
  <title>Output</title>
  <script>
    function myFunction() {
      document.getElementById("demo").innerHTML = "Text";
      document.write(5 + 6);
    }
  </script>
</head>
<body>
  <p id="demo">
    <button onclick="myFunction()">Touch me</button>
  </p>
</body>
</html>

预期输出是 - 文本 11. 但只有 11 个可见。

【问题讨论】:

    标签: javascript html output document.write


    【解决方案1】:

    document.write 将删除您之前拥有的所有内容。您最初将 ID 为demo 的元素的innerHTML 设置为Text,但随后您使用的是document.write,这将完全删除您现有的html 并将其替换为11。您可以将数字的总和附加到Text

    function myFunction() {
      const num = 5 + 6;
      document.getElementById("demo").innerHTML = "Text " + num;
      //document.write(5 + 6);
    
    }
    <p id="demo">
      <button onclick="myFunction()">Touch me</button>
    </p>

    如果您没有任何html 代码,请使用textContent 而不是innerHTML

    function myFunction() {
      document.getElementById("demo").textContent = `Text ${5+6}`;
    }
    <p id="demo">
      <button onclick="myFunction()">Touch me</button>
    </p>

    【讨论】:

      【解决方案2】:

      将脚本放在&lt;head&gt; 不是问题。

      write() 方法主要用于测试:如果在 HTML 文档完全加载后使用,它将删除所有现有的 HTML

      尝试使用innerHTML 属性本身附加内容。

      有关写入的更多信息: https://developer.mozilla.org/en-US/docs/Web/API/Document/write

      【讨论】:

        【解决方案3】:

        您可以将字符串 Text 连同这些数字一起传递给write function

        document.write(`Text ${5+6}`)
        

        <html>
        
        <head>
          <title>Output</title>
          <script>
            function myFunction() {
              document.write(`Text ${5+6}`);
        
            }
          </script>
        
        </head>
        
        <body>
          <p id="demo">
            <button onclick="myFunction()">Touch me</button>
          </p>
        
        
        </body>
        
        </html>

        【讨论】:

          猜你喜欢
          • 2013-06-13
          • 1970-01-01
          • 1970-01-01
          • 2011-05-16
          • 2020-05-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多