代码之家  ›  专栏  ›  技术社区  ›  Aditya

如何在html中显示javascript变量的值?[关闭]

  •  -8
  • Aditya  · 技术社区  · 8 年前

    我想显示输入值点击按钮“去”。 输入值存储在名为“value”的变量中,并在id=“show”中可见。

    <html>
    <head>
    </head>
    
    <body>
    
    <div>
    <input type="text" id="input" />
    <button onclick="go()">Click</button>
    </div>
    
    <div id="show" style="display: none;">
    <p>${value}</p>
    </div>
    
    <script>
    
    
    function go() {
        document.getElementById('show').style.display = "block";
       let value = document.getElementById('input').value;
    }
    </script>
    </body>
    
    </html>
    2 回复  |  直到 8 年前
        1
  •  1
  •   Scott Marcus    8 年前

    你只要把 .textContent 它将显示在变量中的元素的。不需要隐藏/显示元素,因为元素 文本内容 一开始是空的(所以它最初不会显示任何内容)。

    <html>
    <head>
      <title>Using form data in the page</title>
    </head>
    <body>
      <div>
        <input type="text" id="input">
        <button onclick="go()">Click</button>
      </div>
    
      <div id="show"></div>
    
      <script>
        function go() {
          let value = document.getElementById('input').value;
          document.getElementById('show').textContent = value;
        }
      </script>
    </body>
    </html>
        2
  •  1
  •   mplungjan    8 年前
    • 使用type=“按钮”
    • 使用值更新p,不隐藏和不引人注目的事件处理:

    document.querySelector("#go").onclick=function() {
      document.querySelector('#show>p').textContent = document.getElementById('input').value;
    }
    <div>
      <input type="text" id="input" />
      <button type="button" id="go">Click</button>
    </div>
    
    <div id="show">
      <p></p>
    </div>