如何获得两个输出?

时间:2019-06-09 15:25:02

标签: javascript html output document.write

我正在使用document.write()运行一些基本测试用例,它会删除head标签中的所有现有HTML。仅当我将脚本放在<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个可见。

3 个答案:

答案 0 :(得分:4)

document.write将删除您之前的所有内容。您最初是将ID为innerHTML的元素demo设置为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>

答案 1 :(得分:0)

将脚本放在<head>中不是问题。

  

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

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

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

答案 2 :(得分:0)

您可以将字符串文本和这些数字一起传递给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>