【问题标题】:How to add HTML in between script tag如何在脚本标签之间添加 HTML
【发布时间】:2021-08-19 18:04:18
【问题描述】:

例如这是我的代码

<html>
  <head><title>Document</title></head>
  <body>
    <script>
      let input0 = parseInt(prompt("Write a number"))
      let input1 = parseInt(prompt("Write an other number"))
      if (input0 === input1){
        //Here I want to print some text on webpage intead of
        //using document.write or console.log
      }
    </script>
  </body>
</html>

现在我想在 h1 标签中打印一个文本,但是如果条件满足,我该如何执行这个任务

【问题讨论】:

标签: javascript html


【解决方案1】:
  1. 使用 createElement("H1") 创建 h1 标签
  2. 使用 createTextNode("") 创建文本内容并将其附加到 h1 标记
  3. 将 h1 标签附加到 document.body

代码如下:

<html>
  <head>
    <title>Document</title>
  </head>
  <body>
    <script>
      let input0 = parseInt(prompt("Write a number"));
      let input1 = parseInt(prompt("Write an other number"));
      if (input0 === input1) {
        //Here I want to print some text on webpage intead of
        //using document.write or console.log
        var h1 = document.createElement("H1");
        var text = document.createTextNode("Hi there!");
        h1.append(text);
        document.body.append(h1);
      }
    </script>
  </body>
</html>

【讨论】:

  • 向正文添加元素是可以的,但您的方法不会将 h1 添加到确切的位置。它只添加到正文标签的末尾。
【解决方案2】:

其实这是错误的做法。您应该在正文标记的末尾添加一个脚本标记。而且你必须添加一个容器,你想在其中添加你的 H1 标签。

<html>
  <head>
    <title>Document</title>
  </head>
  <body>
    <div class="h1-container"></div>
    <script>
      let input0 = parseInt(prompt("Write a number"));
      let input1 = parseInt(prompt("Write an other number"));
      if (input0 === input1) {
        //Here I want to print some text on webpage intead of
        //using document.write or console.log
        const container = document.querySelector(".h1-container");
        const h1 = document.createElement("H1");
        const text = document.createTextNode("Hi there!");
        h1.append(text);
        container.append(h1);
      }
    </script>
  </body>
</html>

【讨论】:

    猜你喜欢
    • 2022-07-06
    • 2020-12-21
    • 2012-12-08
    • 1970-01-01
    • 2022-01-21
    • 2023-04-08
    • 2022-08-16
    • 2012-03-13
    • 2017-12-27
    相关资源
    最近更新 更多